Skip to content

Commit 1c7b5db

Browse files
Merge pull request #5 from Mohitkumar6122/patch-5
Create 241.cpp
2 parents 99efd25 + 0955d1f commit 1c7b5db

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

LeetCode/241.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
unordered_map<string, vector<int>> ma ;
3+
public:
4+
vector<int> diffWaysToCompute(string expression) {
5+
int n = expression.size() ;
6+
vector<int> ans ;
7+
8+
for(int i = 0; i < n; ++i){
9+
char c = expression[i] ;
10+
if (c == '*' || c == '+' || c == '-'){
11+
vector<int> n1, n2 ;
12+
string s1 = expression.substr(0, i), s2 = expression.substr(i + 1) ;
13+
// cout << s1 << " " << s2 ;
14+
15+
n1 = (ma.find(s1) != ma.end()) ? ma[s1] : diffWaysToCompute(s1) ;
16+
n2 = (ma.find(s2) != ma.end()) ? ma[s2] : diffWaysToCompute(s2) ;
17+
18+
19+
for(auto x : n1){
20+
for(auto y : n2){
21+
if (c == '-') ans.push_back(x - y) ;
22+
else if (c == '+') ans.push_back(x + y) ;
23+
else ans.push_back(x * y) ;
24+
}
25+
}
26+
}
27+
}
28+
if(ans.empty()) ans.push_back(stoi(expression)) ;
29+
ma[expression] = ans ;
30+
return ans ;
31+
32+
}
33+
};
34+
/*
35+
Input: expression = "2-1-1"
36+
Output: [0,2]
37+
Explanation:
38+
((2-1)-1) = 0
39+
(2-(1-1)) = 2
40+
*/

0 commit comments

Comments
 (0)