-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddOperators.cpp
More file actions
43 lines (33 loc) · 1.19 KB
/
addOperators.cpp
File metadata and controls
43 lines (33 loc) · 1.19 KB
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
class Solution {
public:
void solve(int ind, string s, int target, vector<string>& res, string tmp, long long prev, long long sum) {
if (ind == s.size()) {
if (sum == target)
res.push_back(tmp);
return;
}
string st = "";
long long curr = 0;
for (int i = ind; i < s.size(); i++) {
if (i > ind && s[ind] == '0')
break;
st += s[i];
curr = stoll(st);
if (ind == 0)
solve(i + 1, s, target, res, tmp + st, curr, curr);
else {
solve(i + 1, s, target, res, tmp + "+" + st, curr, sum + curr);
solve(i + 1, s, target, res, tmp + "-" + st, -curr, sum - curr);
solve(i + 1, s, target, res, tmp + "*" + st, prev * curr, sum - prev + prev * curr);
}
}
return;
}
vector<string> addOperators(string s, int target) {
vector<string> res;
string tmp = "";
long long prev = 0;
solve(0, s, target, res, tmp, prev, 0);
return res;
}
};