File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments