public boolean judgePoint24(int[] nums) { List<Double> list = new ArrayList<>(); for (int i : nums) { list.add((double) i); } return recursion(list); }
private boolean recursion(List<Double> list) { // recursive: 开头部分都是递归终止条件 if (list.size() == 1) { if (Math.abs(list.get(0) - 24.0) < 0.001) return true; return false; } for (int i = 0; i < list.size(); ++i) { for (int j = i + 1; j < list.size(); ++j) { List<Double> newList = new ArrayList<>(); for (int k=0; k < list.size(); ++k) { if (k != i && k != j) newList.add(list.get(k)); } double a = list.get(i), b = list.get(j); newList.add(a + b); if (recursion(newList)) return true; newList.set(newList.size() - 1, a - b); if (recursion(newList)) return true; newList.set(newList.size() - 1, b - a); if (recursion(newList)) return true; newList.set(newList.size() - 1, a * b); if (recursion(newList)) return true; newList.set(newList.size() - 1, a / b); if (recursion(newList)) return true; newList.set(newList.size() - 1, b / a); if (recursion(newList)) return true; } } return false; }