-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path282.expression-add-operators.cpp
55 lines (47 loc) · 1.32 KB
/
282.expression-add-operators.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
class Solution {
private:
int target;
string num;
void dfs(int pos, long last, long sum, string path, vector<string>& res){
if (pos == num.size())
{
if (sum == target)
{
res.push_back(path);
}
return;
}
long curVal = 0;
string cur = "";
for(auto i = pos; i < num.size(); ++i)
{
curVal = curVal * 10 + num[i] - '0';
cur += num[i];
if (pos == 0)
{
dfs(i + 1, curVal, curVal, path + cur, res);
}
else
{
dfs(i + 1, curVal, sum + curVal , path + "+" + cur, res);
dfs(i + 1, -curVal, sum - curVal , path + "-" + cur, res);
dfs(i + 1, curVal * last, sum - last + curVal * last , path + "*" + cur, res);
}
if (num[pos] == '0') {
break;
}
}
}
public:
vector<string> addOperators(string num, int target) {
if (num.size() == 0)
{
return vector<string>();
}
this->target = target;
this->num = num;
vector<string> res;
dfs(0, 0, 0, "", res);
return res;
}
};