forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expression Add Operators.cpp
37 lines (32 loc) · 1.02 KB
/
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
// Runtime: 571 ms (Top 55.38%) | Memory: 115.7 MB (Top 27.93%)
class Solution {
public:
vector<string> res;
string s;
int target, n;
void solve(int it, string path, long long resSoFar, long long prev){
if(it == n){
if(resSoFar == target) res.push_back(path);
return;
}
long long num = 0;
string tmp;
for(auto j = it; j < n; j++){
if(j > it && s[it] == '0') break;
num = num * 10 + (s[j] - '0');
tmp.push_back(s[j]);
if(it == 0) solve(j + 1, tmp, num, num);
else{
solve(j + 1, path + "+" + tmp, resSoFar + num, num);
solve(j + 1, path + '-' + tmp, resSoFar - num, -num);
solve(j + 1, path + '*' + tmp, resSoFar - prev + prev * num, prev * num);
}
}
}
vector<string> addOperators(string num, int target) {
this -> target = target;
s = num, n = num.size();
solve(0, "", 0, 0);
return res;
}
};