LeetCode 679. 24 点游戏
原题链接
简单
作者:
autumn_0
,
2025-01-13 21:32:03
,
所有人可见
,
阅读 3
class Solution {
public boolean judgePoint24(int[] cards) {
List<Double> list = new ArrayList<>();
for(int i: cards) {
list.add((double) i);
}
return dfs(list);
}
public boolean dfs(List<Double> list) {
if(list.size() == 1) {
return Math.abs(list.get(0) - 24) < 1e-8;
}
for(int i = 0; i < list.size(); i ++ ) {
for(int j = 0; j < list.size(); j ++ ) {
if(i != j) {
double a = list.get(i);
double b = list.get(j);
if(dfs(get(list, i, j, a + b))) return true;
if(dfs(get(list, i, j, a - b))) return true;
if(dfs(get(list, i, j, a * b))) return true;
if(dfs(get(list, i, j, a / b))) return true;
}
}
}
return false;
}
public List<Double> get(List<Double> list, int i, int j, double x) {
List<Double> res = new ArrayList<>();
for(int k = 0; k < list.size(); k ++ ) {
if(k != i && k != j) {
res.add(list.get(k));
}
}
res.add(x);
return res;
}
}