Skip to content

Commit ab70488

Browse files
authored
Create 241. Different Ways to Add Parentheses (#589)
2 parents 4c49308 + eecf5e6 commit ab70488

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution {
2+
public:
3+
map<pair<int,int>,vector<int>>dp;
4+
vector<int> solve(int i,int j,string &s){
5+
if(j-i+1<=2){
6+
string temp=s.substr(i,(j-i+1));
7+
cout<<temp<<endl;
8+
return {stoi(temp)};
9+
}
10+
11+
if(dp.count({i,j})>0) return dp[{i,j}];
12+
13+
vector<int>ans;
14+
15+
for(int k=i;k<=j;k++){
16+
if(!isdigit(s[k])){
17+
vector<int> temp=solve(i,k-1,s);
18+
vector<int> tmp=solve(k+1,j,s);
19+
20+
if(s[k]=='+'){
21+
for(int it=0;it<temp.size();it++){
22+
for(int itt=0;itt<tmp.size();itt++){
23+
ans.push_back(temp[it]+tmp[itt]);
24+
}
25+
}
26+
}
27+
else if(s[k]=='*'){
28+
for(int it=0;it<temp.size();it++){
29+
for(int itt=0;itt<tmp.size();itt++){
30+
ans.push_back(temp[it]*tmp[itt]);
31+
}
32+
}
33+
}
34+
else if(s[k]=='-'){
35+
for(int it=0;it<temp.size();it++){
36+
for(int itt=0;itt<tmp.size();itt++){
37+
ans.push_back(temp[it]-tmp[itt]);
38+
}
39+
}
40+
}
41+
}
42+
}
43+
return dp[{i,j}]=ans;
44+
}
45+
vector<int> diffWaysToCompute(string s) {
46+
dp.clear();
47+
return solve(0,s.size()-1,s);
48+
}
49+
};

0 commit comments

Comments
 (0)