-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdifferentWaystoAddParentheses.cpp
More file actions
36 lines (34 loc) · 1.14 KB
/
differentWaystoAddParentheses.cpp
File metadata and controls
36 lines (34 loc) · 1.14 KB
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
// Source: https://leetcode.com/problems/different-ways-to-add-parentheses/
// Author: Miao Zhang
// Date: 2021-01-28
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for (int i = 0; i < input.size(); i++) {
if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(input.substr(i + 1));
for (auto l: left) {
for (auto r: right) {
if (input[i] == '+') {
res.push_back(l + r);
} else if (input[i] == '-') {
res.push_back(l - r);
} else {
res.push_back(l * r);
}
}
}
}
}
if (res.empty()) {
int num = 0;
for (auto c: input) {
num = num * 10 + c - '0';
}
res.push_back(num);
}
return res;
}
};