给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +
, -
以及 *
。
示例 1:
输入:"2-1-1"
输出:[0, 2]
解释: ((2-1)-1) = 0 (2-(1-1)) = 2
示例 2:
输入:"2*3-4*5"
输出:[-34, -14, -10, -10, 10]
解释: (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
思路:采用分治的思想,对于string的每一个operator,都看作:左集合operator右集合的结果,所以递归调用计算出左部分的集合left(vector<int> left),递归调用计算右部分的集合right(vector<int> right),对于操作的每一个operator都看成左集合left和右集合right的遍历操作,对每个元素都进行operator操作。最后放到res中,如果res为空,表示这次input只有数字,则把字符串转为数字压进res中。
参考代码:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
int length = input.size();
for (int i = 0; i < length; i++) {
if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(input.substr(i + 1));
for (int j = 0; j < left.size(); j++) {
for (int k = 0; k < right.size(); k++) {
if (input[i] == '+') {
res.push_back(left[j] + right[k]);
}
else if (input[i] == '-') {
res.push_back(left[j] - right[k]);
}
else {
res.push_back(left[j] * right[k]);
}
}
}
}
}
if (res.empty()) {
res.push_back(atoi(input.c_str()));
}
return res;
}