-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDifferent_Ways_to_Add_Parentheses.cpp
More file actions
46 lines (45 loc) · 1.41 KB
/
Different_Ways_to_Add_Parentheses.cpp
File metadata and controls
46 lines (45 loc) · 1.41 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
37
38
39
40
41
42
43
44
45
46
class Solution
{
public:
/*Different Ways to Add Parentheses,递归*/
vector<int> diffWaysToCompute(string input)
{
int length = input.size();
vector<int> res;
for (int i = 0; i < length; i++)
{
char c = input[i];
//操作符
if (ispunct(c))
{
vector<int> l_res = diffWaysToCompute(input.substr(0, i)); //左端结果
vector<int> r_res = diffWaysToCompute(input.substr(i + 1)); //右端结果
//组合
for (int j = 0; j < l_res.size(); j++)
{
for (int k = 0; k < r_res.size(); k++)
{
switch (c)
{
case '+':
res.push_back(l_res[j] + r_res[k]);
break;
case '-':
res.push_back(l_res[j] - r_res[k]);
break;
case '*':
res.push_back(l_res[j] * r_res[k]);
break;
default:
break;
}
}
}
}
}
//字符串转化为数字
if (res.empty())
res.push_back(stoi(input));
return res;
}
};