forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path241.Different-Ways-to-Add-Parentheses_v2.cpp
49 lines (46 loc) · 1.22 KB
/
241.Different-Ways-to-Add-Parentheses_v2.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
45
46
47
48
49
class Solution {
vector<int>nums;
vector<char>ops;
vector<int> dp[21][21];
public:
vector<int> diffWaysToCompute(string input)
{
for (int i=0; i<input.size(); i++)
{
int j = i;
while (j<input.size() && isdigit(input[j]))
j++;
nums.push_back(stoi(input.substr(i, j-i)));
if (j<input.size()) ops.push_back(input[j]);
i = j;
}
int n = nums.size();
helper(0, n-1);
return dp[0][n-1];
}
void helper(int a, int b)
{
if (!dp[a][b].empty())
return;
if (a==b)
{
dp[a][b] = {nums[a]};
return;
}
for (int i=a; i<b; i++)
{
helper(a,i);
helper(i+1,b);
for (int x: dp[a][i])
for (int y: dp[i+1][b])
{
if (ops[i]=='+')
dp[a][b].push_back(x+y);
else if (ops[i]=='-')
dp[a][b].push_back(x-y);
else if (ops[i]=='*')
dp[a][b].push_back(x*y);
}
}
}
};