[LeetCode] Different Ways to Add Parentheses

241. Different Ways to Add Parentheses

Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.

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
class Solution {
unordered_map<string, vector<int>> dp;
public:
vector<int> diffWaysToCompute(string& exp) {
if(dp.count(exp)) return dp[exp];
vector<int>& res = dp[exp];
for(int i = 0; i < exp.length(); i++) {
if(!isdigit(exp[i])) {
string left = exp.substr(0,i);
string right = exp.substr(i + 1);
vector<int> leftResult = diffWaysToCompute(left);
vector<int> rightResult = diffWaysToCompute(right);
for(int l : leftResult) {
for(int r : rightResult) {
if(exp[i] == '+') {
res.push_back(l + r);
} else if(exp[i] == '-') {
res.push_back(l - r);
} else {
res.push_back(l * r);
}
}
}
}
}

if(res.empty()) {
res.push_back(stoi(exp));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/07/PS/LeetCode/different-ways-to-add-parentheses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.