微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何修改此递归回溯算法倒计时:游戏以找到所有解决方案而不是一个?

如何解决如何修改此递归回溯算法倒计时:游戏以找到所有解决方案而不是一个?

我编写了一个方法,该方法使用递归和回溯来找到倒计时问题的一个解决方案。我现在想要做的是修改这个方法,以便它可以找到所有可能的解决方案。 该程序包括从一组初始 6 个数字中获取目标数字(从 101 到 999 的自然整数),对这组六个数字使用基本算术运算(+、-、×、÷)。 我能够找到第一个解决方案,但我想找到所有解决方案,然后再选择最好的(操作较少的那个)。 这是我现在掌握的代码

private static boolean backtracking(ArrayList<Integer> aux,int len,int total,ArrayList<String> operations) {
    
    for(int i = 0; i < len; i++) {
        
        if(aux.get(i) == total) {
            return true;
        }
        
        for(int j = i + 1; j < len; j++) {
            for(int k = 0; k < operations.size(); k++) {
                
                int res =  doOperation(operations.get(k),aux.get(i),aux.get(j));
                
                if(res != 0) {
                    
                    int savei = aux.get(i);
                    int savej = aux.get(j);
                    aux.set(i,res);
                    aux.set(j,aux.get(len-1));
                    
                    if(backtracking(aux,len-1,total,operations)) {
                        solution.add(Math.max(savei,savej) + " " + operations.get(k) + " " + Math.min(savei,savej) + " = " + res);
                        return true;
                    }
                    
                    aux.set(i,savei);
                    aux.set(j,savej);
                    
                }
                
            }
            
        }
        
    }
    
    return false;
    
}

private static int doOperation(String operation,int x,int y) {
    
    int r = 0;
    
    if(operation.equals("+")) {
        
        r = x + y;
        
        if(r <= x || r <= y) {
            return 0;
        }else {
            return r;
        }
        
    }else if(operation.equals("-")) {
        
        if(x < y) {
            return y - x;
        }else {
            return x - y;
        }
        
    }else if(operation.equals("*")) {
        
        r = x * y;
        
        if(r <= x || r <= y) {
            return 0;
        }else {
            return r;
        }
        
    }else if(operation.equals("/")) {
        
        if(x < y) {
            int t = x;
            x = y;
            y = t;
        }
        
        if(x % y == 0) {
            return x / y;
        }else {
            return 0;
        }
        
    }else {
        return r;
    }
    
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。