-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdifferent-ways-to-add-parentheses(AC).cpp
82 lines (74 loc) · 1.81 KB
/
different-ways-to-add-parentheses(AC).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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
num.clear();
op.clear();
tokenize(input);
int n = num.size();
vector<int> ans;
compute(0, n - 1, ans);
sort(ans.begin(), ans.end());
return ans;
}
private:
vector<int> num;
vector<char> op;
void tokenize(const string &s) {
int ls = s.length();
int i = 0;
int val;
while (i < ls) {
val = 0;
while (i < ls && isdigit(s[i])) {
val = val * 10 + (s[i] - '0');
++i;
}
num.push_back(val);
if (i >= ls) {
break;
}
op.push_back(s[i++]);
}
}
int calc(int x, int y, char op) {
switch(op) {
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
default:
return 0;
}
}
void compute(int ll, int rr, vector<int> &ans) {
if (ll == rr) {
ans.push_back(num[ll]);
return;
}
int i, j1, j2;
vector<int> ans1;
vector<int> ans2;
int m1, m2;
for (i = ll + 1; i <= rr; ++i) {
compute(ll, i - 1, ans1);
compute(i, rr, ans2);
m1 = ans1.size();
m2 = ans2.size();
for (j1 = 0; j1 < m1; ++j1) {
for (j2 = 0; j2 < m2; ++j2) {
ans.push_back(calc(ans1[j1], ans2[j2], op[i - 1]));
}
}
ans1.clear();
ans2.clear();
}
}
};