-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathDifferent_Ways_to_Add_Parentheses.cpp
43 lines (38 loc) · 1.14 KB
/
Different_Ways_to_Add_Parentheses.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
inline bool isOperator(char ch) {
return (ch == '-' or ch == '*' or ch == '+');
}
int eval(int a, int b, char op) {
int val;
if(op == '*') {
val = a * b;
} else if(op == '-') {
val = a - b;
} else if(op == '+') {
val = a + b;
}
return val;
}
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
if(input.empty()) return result;
int n = (int)input.length();
for(int i = 0; i < n; ++i) {
if(!isOperator(input[i])) {
continue;
}
vector<int> leftValues = diffWaysToCompute(input.substr(0, i));
vector<int> rightValues = diffWaysToCompute(input.substr(i + 1));
for(int leftVal: leftValues) {
for(int rightVal: rightValues) {
result.push_back(eval(leftVal, rightVal, input[i]));
}
}
}
if(result.empty()) {
result.push_back(stoi(input));
}
return result;
}
};