-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
56 lines (54 loc) · 1.87 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
private final char[] ops = {'+', '-', '*', '/'};
public boolean judgePoint24(int[] cards) {
List<Double> nums = new ArrayList<>();
for (int num : cards) {
nums.add((double) num);
}
return dfs(nums);
}
private boolean dfs(List<Double> nums) {
int n = nums.size();
if (n == 1) {
return Math.abs(nums.get(0) - 24) < 1e-6;
}
boolean ok = false;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i != j) {
List<Double> nxt = new ArrayList<>();
for (int k = 0; k < n; ++k) {
if (k != i && k != j) {
nxt.add(nums.get(k));
}
}
for (char op : ops) {
switch (op) {
case '/' -> {
if (nums.get(j) == 0) {
continue;
}
nxt.add(nums.get(i) / nums.get(j));
}
case '*' -> {
nxt.add(nums.get(i) * nums.get(j));
}
case '+' -> {
nxt.add(nums.get(i) + nums.get(j));
}
case '-' -> {
nxt.add(nums.get(i) - nums.get(j));
}
}
ok |= dfs(nxt);
if (ok) {
return true;
}
nxt.remove(nxt.size() - 1);
}
}
}
}
return ok;
}
}