-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpressions add operators.cpp
44 lines (44 loc) · 1.6 KB
/
expressions 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
class Solution
{
public:
void generate(string &num, int target, int curr, vector<string> &res, string build, long long int prevNumber, long long int currSum, int n)
{
if (curr == num.size())
{
if (currSum == target)
{
res.push_back(build);
}
return;
}
for (int len = 1; len <= (n - curr); len++)
{
string number = num.substr(curr, len);
if (number[0] == '0' && number.size() > 1)
{
continue;
}
long long int currNum = stoll(number);
generate(num, target, curr + len, res, build + "+" + number, currNum, currSum + currNum, n);
generate(num, target, curr + len, res, build + "-" + number, -currNum, currSum - currNum, n);
generate(num, target, curr + len, res, build + "*" + number, currNum * prevNumber, currSum - prevNumber + currNum * prevNumber, n);
}
}
vector<string> addOperators(string num, int target)
{
vector<string> res;
int n = num.size();
for (int len = 1; len <= n; len++)
{
string number = num.substr(0, len);
if (number[0] == '0' && number.size() > 1)
{
continue;
}
long long int currNum = stoll(number);
generate(num, target, len, res, number, currNum, currNum, n);
}
return res;
}
};
// leetcode - 282