Different Ways to Add Parentheses
题目
leetcode题目
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 1
Input: 2-1-1
.
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: 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]
解决
想法:这道题采用分治算法,以符号+、-、*
为标志位,当遇到这三个符号时候,以符号为分界线,将式子分为左右两部分,分别计算结果,之后再合并,得到最终结果。具体思路可以参照上面题目例子给出的过程
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
int len = input.size();
vector<int> result;
for (int k = 0; k < len; k++) {
if (input[k] == '+' || input[k] == '-' || input[k] == '*') { // 分割式子
vector<int> left = diffWaysToCompute(input.substr(0, k)); // 左边式子的结果
vector<int> right = diffWaysToCompute(input.substr(k + 1)); // 右边式子的结果
int n1 = left.size();
int n2 = right.size();
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
if (input[k] == '+') {
result.push_back(left[i] + right[j]);
} else if (input[k] == '-') {
result.push_back(left[i] - right[j]);
} else if (input[k] == '*') {
result.push_back(left[i] * right[j]);
}
}
}
}
}
if (result.empty()) { // 输入的字符串没有符号,只有数字
result.push_back(atoi(input.c_str())); // 将字符串变成数字
}
return result;
}
};