您的位置:首页 > Web前端

Leetcode 241. Different Ways to Add Parentheses

2018-03-01 14:43 281 查看
原题:

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are
+
,
-
and
*
.

Example 1Input:
"2-1-1"
.
((2-1)-1) = 0
(2-(1-1)) = 2
Output:
[0, 2]


Example 2Input:
"2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output:
[-34, -14, -10, -10, 10]

 
解决方法:
 对每一个'+'、'-'、'*'号,都可以分成前后两部分分别计算结果,然后将两个结果排列组合到一块即可。

代码:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for(int i = 0; i < input.size(); i++){
char ch = input[i];
if (ch == '+' || ch == '-' || ch == '*'){
vector<int> v1 = diffWaysToCompute(input.substr(0, i));
vector<int> v2 = diffWaysToCompute(input.substr(i + 1));
for(auto num1 : v1){
for(auto num2: v2){
int num = 0;
if (ch == '+')
num = num1 + num2;
else if (ch == '-')
num = num1 - num2;
else
num = num1 * num2;
res.push_back(num);
}
}
}
}

return res.size() ? res :vector<int>{ stoi(input)};
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode cplusplus