241. Different Ways to Add Parentheses
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +
, -
and *
.
Example 1
Input: "2-1-1"
.
((2-1)-1) = 0 (2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
vector<int> remem[500][500];
2
class Solution {
3
public:
4
vector<int> divides(string input, int start, int end, int* d) {
5
vector<int> ans;
6
if (remem[d[start]][d[end]].size() != 0) return remem[d[start]][d[end]];
7
if (d[start] == d[end]) {
8
int x = 0;
9
for (int i = start; i <= end; i++) x = x*10+input[i]-'0';
10
ans.push_back(x);
11
if (d[start] < 500) remem[d[start]][d[end]] = ans;
12
return ans;
13
}
14
for (int k = start; k <= end; k++)
15
if (input[k] < '0' || input[k] > '9') {
16
vector<int> left = divides(input, start, k-1, d),
17
right = divides(input, k+1, end, d);
18
for (int i = 0; i < left.size(); i++)
19
for (int j = 0; j < right.size(); j++)
20
if (input[k] == '+') ans.push_back(left[i]+right[j]);
21
else if (input[k] == '-') ans.push_back(left[i]-right[j]);
22
else ans.push_back(left[i]*right[j]);
23
}
24
if (d[start] < 500 && d[end] < 500) remem[d[start]][d[end]] = ans;
25
return ans;
26
}
27
vector<int> diffWaysToCompute(string input) {
28
vector<int> ans;
29
for (int i = 0; i < 500; i++)
30
for (int j = 0; j < 500; j++)
31
remem[i][j].clear();
32
if (input.size() == 0) return ans;
33
int *p, t = 0;
34
p = new int[input.length()];
35
for (int i = 0; i < input.length(); i++) {
36
p[i] = t;
37
if (input[i] < '0' || input[i] > '9') t++;
38
}
39
ans = divides(input, 0, input.size()-1, p);
40
delete[] p;
41
return ans;
42
}
43
};