一行四个数字 (JQK 分别被替换成11,12,13)单空格分割,另一行输入 m
可以输出1
否则输出0
13 13 13 13 24
0
提示:
注意运算符优先级
import java.util.*;
// 注意:可以任意改变扑克牌的顺序, 其实就是考虑了括号的、所有情况的
// 🍓
// 回溯:初始4张牌, 任取2张进行+-*/, 结果放回, 变3张牌,下一层..直至仅剩1张
public class Main {
private static boolean find = false; // 找到一种
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < 4; i++) nums.add(in.nextInt());
int m = in.nextInt();
backtrack(nums, m);
System.out.print(find ? 1 : 0);
}
// 回溯
private static void backtrack(List<Integer> nums, int target) {
if (find || nums.size() == 1) { // 出口
if (!find && nums.get(0) == target) find = true;
return;
}
for (int i = 0; i < nums.size() && !find; i++) {
for (int j = 0; j < nums.size() && !find; j++) {
if (i == j) continue;
Integer x = nums.get(i), y = nums.get(j); // 任取两个数
int res = -1;
for (int k = 0; k <= 3; k++) { // +-*/ 四种
if (k == 0) res = x + y;
else if (k == 1) res = x - y;
else if (k == 2) res = x * y;
else if (y != 0) res = x / y;
List<Integer> numsCopy = new ArrayList<>(nums);
numsCopy.remove(x);
numsCopy.remove(y);
numsCopy.add(res);
backtrack(numsCopy, target); // 4 * 11 / 3 -9 = 23
}
}
}
}
}