题解 | #24点游戏算法#
24点游戏算法
http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] strs = scan.nextLine().split(" ");
ArrayList<Integer> nums = new ArrayList<>();
for (String str : strs) {
nums.add(Integer.valueOf(str));
}
for (int num : nums) {
ArrayList<Integer> copyArr = new ArrayList<>(nums);
copyArr.remove(Integer.valueOf(num));
if (process(copyArr, Double.valueOf(num))) {
System.out.println("true");
return;
}
}
System.out.println("false");
}
public static boolean process(ArrayList<Integer> nums, double total) {
if (nums.size() == 0) {
if ((double) 24 == total) {
return true;
} else {
return false;
}
}
for (int num : nums) {
ArrayList<Integer> copyArr = new ArrayList<>(nums);
copyArr.remove(Integer.valueOf(num));
if (process(copyArr, total + num)) {
return true;
}
if (process(copyArr, total - num)) {
return true;
}
if (process(copyArr, total * num)) {
return true;
}
if (Integer.valueOf(num) != 0) {
if (process(copyArr, total / num)) {
return true;
}
}
}
return false;
}
}