Skip to content

Commit

Permalink
Update 241.Different-Ways-to-Add-Parentheses_v2.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Sep 27, 2021
1 parent 1a00847 commit a661548
Showing 1 changed file with 14 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class Solution {
vector<int>nums;
vector<char>ops;

vector<int> dp[21][21];
public:
vector<int> diffWaysToCompute(string input)
{
Expand All @@ -10,18 +10,17 @@ class Solution {
int j = i;
while (j<input.size() && isdigit(input[j]))
j++;
nums.push_back(stoi(input.substr(i,j-i)));
ops.push_back(input[j]);
i = 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();
vector<vector<vector<int>>>dp(n, vector<vector<int>>(n));
helper(dp, 0, n-1);
return dp[0][n-1];
helper(0, n-1);
return dp[0][n-1];
}

void helper(vector<vector<vector<int>>>&dp, int a, int b)
void helper(int a, int b)
{
if (!dp[a][b].empty())
return;
Expand All @@ -33,10 +32,10 @@ class Solution {

for (int i=a; i<b; i++)
{
helper(dp, a, i);
helper(dp, i+1, b);
for (auto x: dp[a][i])
for (auto y: dp[i+1][b])
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);
Expand All @@ -46,5 +45,5 @@ class Solution {
dp[a][b].push_back(x*y);
}
}
}
}
};

0 comments on commit a661548

Please sign in to comment.