题解 | #24点游戏算法#
24点游戏算法
http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
java dfs
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()) {
double[] a = new double[4];
for (int i = 0; i < 4; i++) {
a[i] = sc.nextInt();
}
boolean[] visited = new boolean[4];
Arrays.fill(visited, true);
if (dfs(a, 0 , 0, visited)) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
private static boolean dfs(double[] a, double res, int idex, boolean[] visited) {
if (idex >= 4) {
return Math.abs(res - 24) == 0;
}
boolean flag = false;
for(int i = 0; i< 4; i++) {
if (visited[i]) {
visited[i] = false;
flag = dfs(a, res + a[i] , idex+1, visited) || dfs(a, res - a[i] , idex+1, visited)|| dfs(a, res * a[i] , idex+1, visited)|| dfs(a, res / a[i] , idex+1, visited);
visited[i] = true;
if (flag == true) {
break;
}
}
}
return flag;
}
}