282. Expression Add Operators
Given a string that contains only digits 0-9
and a target value, return all possibilities to add binary operators (not unary) +
, -
, or *
between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> []
Credits:
Special thanks to @davidtan1890 for adding this problem and creating all test cases.
Solution:
#include <stack>
2
class Solution {
3
public:
4
void divides(vector<string>& ans, string& num, int target, string str, int d, bool flag, stack<long long> nums, stack<char> syms, int state) {
5
if (state == 0) {
6
nums.top() = nums.top()*10+num[d-1]-'0';
7
} else if (state == 1 || state == 2) {
8
while (syms.size()) {
9
long long x = nums.top(); nums.pop();
10
if (syms.top() == '+') nums.top() += x;
11
else if (syms.top() == '-') nums.top() -= x;
12
else nums.top() *= x;
13
syms.pop();
14
}
15
if (state == 1) syms.push('+');
16
else syms.push('-');
17
nums.push(num[d-1]-'0');
18
} else {
19
while (syms.size() && syms.top() == '*') {
20
long long x = nums.top(); nums.pop();
21
nums.top() *= x; syms.pop();
22
}
23
syms.push('*');
24
nums.push(num[d-1]-'0');
25
}
26
if (d == num.length()) {
27
while (syms.size()) {
28
long long x = nums.top(); nums.pop();
29
if (syms.top() == '+') nums.top() += x;
30
else if (syms.top() == '-') nums.top() -= x;
31
else nums.top() *= x;
32
syms.pop();
33
}
34
if (target == nums.top()) ans.push_back(str);
35
return;
36
}
37
if (flag) divides(ans, num, target, str+num[d], d+1, true, nums, syms, 0);
38
divides(ans, num, target, str+"+"+num[d], d+1, num[d]-'0', nums, syms, 1);
39
divides(ans, num, target, str+"-"+num[d], d+1, num[d]-'0', nums, syms, 2);
40
divides(ans, num, target, str+"*"+num[d], d+1, num[d]-'0', nums, syms, 3);
41
}
42
vector<string> addOperators(string num, int target) {
43
vector<string> ans;
44
if (num.length() == 0) return ans;
45
string str; str += num[0];
46
stack<long long> nums; nums.push(0);
47
stack<char> syms;
48
divides(ans, num, target, str, 1, num[0]-'0', nums, syms, 0);
49
return ans;
50
}
51
};