网上搜了一些答案,发现有些答案在3个数运算等于24后就返回true了,明显不对。
这里还是用全排列忽略掉+-*/的优先顺序,然后对每一个排列进行dfs。
import java.util.*;
public class Main {
static ArrayList<Integer> list = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
list.clear();
int[] a = new int[4];
for (int i = 0; i < 4; i++) {
a[i] = sc.nextInt();
}
permutation(a, 0, 4); //求全排列
boolean ok = false;
for(int j = 0;j<list.size()/4;j++){
int[] b = new int[4];
for(int i = 0;i<4;i++){
b[i] = list.get(j*4+i);
}
if(f((double)b[0], b,1)){
ok = true;
break;
}
}
System.out.println(ok);
}
}
public static boolean f(double result, int[] a, int index) {
if (index ==4){
return result == 24;
}
else if(f(result + a[index