-
Notifications
You must be signed in to change notification settings - Fork 0
/
0241_Different_Ways_to_Add_Parentheses.cpp
49 lines (47 loc) · 2.48 KB
/
0241_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
44
45
46
47
48
49
// ███████╗ █████╗ ███╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ██╗ ██╗
// ██╔════╝ ██╔══██╗ ████╗ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║ ██║
// ███████╗ ███████║ ██╔██╗ ██║ ██║ ██║ ███████║ ██████╔╝ ██████╔╝ ███████║
// ╚════██║ ██╔══██║ ██║╚██╗██║ ██║ ██║ ██╔══██║ ██╔═██╗ ██╔══██╗ ██╔══██║
// ███████║ ██║ ██║ ██║ ╚████║ ██████╔╝ ██║ ██║ ██║ ██╗ ██████╔╝ ██║ ██║
// ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops","no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c")
auto init = []() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
return dfs(expression);
}
vector<int> dfs(string exp) {
if (memo.count(exp)) return memo[exp];
if (exp.size() < 3) return {stoi(exp)};
vector<int> ans;
int n = exp.size();
for (int i = 0; i < n; ++i) {
char c = exp[i];
if (c == '-' || c == '+' || c == '*') {
vector<int> left = dfs(exp.substr(0, i));
vector<int> right = dfs(exp.substr(i + 1, n - i - 1));
for (int& a : left) {
for (int& b : right) {
if (c == '-')
ans.push_back(a - b);
else if (c == '+')
ans.push_back(a + b);
else
ans.push_back(a * b);
}
}
}
}
memo[exp] = ans;
return ans;
}
private:
unordered_map<string, vector<int>> memo;
};