-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.ts
49 lines (48 loc) · 1.7 KB
/
Solution.ts
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
function judgePoint24(cards: number[]): boolean {
const ops: string[] = ['+', '-', '*', '/'];
const dfs = (nums: number[]): boolean => {
const n: number = nums.length;
if (n === 1) {
return Math.abs(nums[0] - 24) < 1e-6;
}
let ok: boolean = false;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i !== j) {
const nxt: number[] = [];
for (let k = 0; k < n; k++) {
if (k !== i && k !== j) {
nxt.push(nums[k]);
}
}
for (const op of ops) {
switch (op) {
case '/':
if (nums[j] === 0) {
continue;
}
nxt.push(nums[i] / nums[j]);
break;
case '*':
nxt.push(nums[i] * nums[j]);
break;
case '+':
nxt.push(nums[i] + nums[j]);
break;
case '-':
nxt.push(nums[i] - nums[j]);
break;
}
ok = ok || dfs(nxt);
if (ok) {
return true;
}
nxt.pop();
}
}
}
}
return ok;
};
return dfs(cards);
}