问题描述
我编写了一个方法,该方法使用递归和回溯来找到倒计时问题的一个解决方案。我现在想要做的是修改这个方法,以便它可以找到所有可能的解决方案。 该程序包括从一组初始 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 (将#修改为@)