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
Example 1Input:
Example 2Input:
解决方法:
对每一个'+'、'-'、'*'号,都可以分成前后两部分分别计算结果,然后将两个结果排列组合到一块即可。
代码:
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)};
}
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)) = 2Output:
[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) = 10Output:
[-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 241. Different Ways to Add Parentheses-分治算法
- 【Leetcode】241. Different Ways to Add Parentheses
- leetCode刷题归纳-Divide and Conquer(241. Different Ways to Add Parentheses)
- LeetCode241. Different Ways to Add Parentheses
- LeetCode *** 241. Different Ways to Add Parentheses
- 241. Different Ways to Add Parentheses LeetCode
- LeetCode 241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- 【LeetCode】241. Different Ways to Add Parentheses
- Leetcode 241. Different Ways to Add Parentheses
- 【LeetCode】 241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- Leetcode 241. Different Ways to Add Parentheses[medium]
- LeetCode[241. Different Ways to Add Parentheses] 难度[medium]
- [LeetCode]241. Different Ways to Add Parentheses
- LeetCode 241. Different Ways to Add Parentheses
- leetcode 241. Different Ways to Add Parentheses
- [Leetcode] 241. Different Ways to Add Parentheses 解题报告
- 【LeetCode】241. Different Ways to Add Parentheses
- 【LeetCode】241. Different Ways to Add Parentheses