File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
DifferentWaysToAddParentheses Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<int > diffWaysToCompute (string expression)
4
+ {
5
+ vector<int > results;
6
+
7
+ // Handle base cases
8
+ if (expression.empty ())
9
+ return results;
10
+
11
+ if (expression.length () == 1 )
12
+ return {expression.front () - ' 0' };
13
+
14
+ if (expression.length () == 2 )
15
+ {
16
+ int digit1 = expression.front () - ' 0' ;
17
+ int digit2 = expression.back () - ' 0' ;
18
+ int finalDigit = (digit1*10 ) + digit2;
19
+ return { finalDigit };
20
+ }
21
+
22
+ // Handle main cases
23
+ for (int i=0 ; i<expression.length (); i++)
24
+ {
25
+ int currentChar = expression.at (i);
26
+
27
+ // Skip if digit
28
+ if (isDigit (currentChar))
29
+ continue ;
30
+
31
+ // Reached a operator char
32
+ // Split the expression into left and right parts
33
+ vector<int > leftResults = diffWaysToCompute (expression.substr (0 , i));
34
+ vector<int > rightResults = diffWaysToCompute (expression.substr (i + 1 ));
35
+
36
+ // Combine results from left and right parts
37
+ for (int leftValue : leftResults) {
38
+ for (int rightValue : rightResults) {
39
+ int computedResult = 0 ;
40
+
41
+ // Perform the operation based on the current character
42
+ switch (currentChar) {
43
+ case ' +' :
44
+ computedResult = leftValue + rightValue;
45
+ break ;
46
+ case ' -' :
47
+ computedResult = leftValue - rightValue;
48
+ break ;
49
+ case ' *' :
50
+ computedResult = leftValue * rightValue;
51
+ break ;
52
+ }
53
+
54
+ results.push_back (computedResult);
55
+ }
56
+ }
57
+ }
58
+
59
+ return results;
60
+ }
61
+
62
+ bool isDigit (char c)
63
+ {
64
+ return (c >= ' 0' && c <= ' 9' );
65
+ }
66
+ };
You can’t perform that action at this time.
0 commit comments