forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
58 lines (56 loc) · 1.78 KB
/
Solution.cpp
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
57
58
class Solution {
public:
bool judgePoint24(vector<int>& cards) {
vector<double> nums;
for (int num : cards) {
nums.push_back(static_cast<double>(num));
}
return dfs(nums);
}
private:
const char ops[4] = {'+', '-', '*', '/'};
bool dfs(vector<double>& nums) {
int n = nums.size();
if (n == 1) {
return abs(nums[0] - 24) < 1e-6;
}
bool ok = false;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i != j) {
vector<double> nxt;
for (int k = 0; k < n; ++k) {
if (k != i && k != j) {
nxt.push_back(nums[k]);
}
}
for (char op : ops) {
switch (op) {
case '/':
if (nums[j] == 0) {
continue;
}
nxt.push_back(nums[i] / nums[j]);
break;
case '*':
nxt.push_back(nums[i] * nums[j]);
break;
case '+':
nxt.push_back(nums[i] + nums[j]);
break;
case '-':
nxt.push_back(nums[i] - nums[j]);
break;
}
ok |= dfs(nxt);
if (ok) {
return true;
}
nxt.pop_back();
}
}
}
}
return ok;
}
};