给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 104 。
输入:expression = “2-1-1”
输出:[0,2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
链接:https://leetcode.cn/problems/different-ways-to-add-parentheses
class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
vector<int> res;
for (int i = 0; i < expression.size(); i++) {
char c = expression[i];
if (c == '+' || c == '-' || c == '*') {
auto res1 = diffWaysToCompute(expression.substr(0, i));
auto res2 = diffWaysToCompute(expression.substr(i+1));
for (auto num1 : res1) {
for (auto num2 : res2) {
if (c == '+') {
res.push_back(num1 + num2);
}
else if (c == '-') {
res.push_back(num1 - num2);
}
else {
res.push_back(num1 * num2);
}
}
}
}
}
if (res.empty()) { //result数组中没有运算符
res.push_back(stoi(expression));
}
return res;
}
};