LeetCode——241. 为运算表达式设计优先级(递归)
程序员文章站
2024-03-22 16:23:22
...
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +
, -
以及 *
。
示例 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
代码:
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
// 递归
// 第一位和最后一位不为运算符,故跳过
for (size_t i = 1; i < input.size() - 1; i++){
if (input[i] == '+' || input[i] == '-' || input[i] == '*'){
vector<int> result1 = diffWaysToCompute(input.substr(0, i));
vector<int> result2 = diffWaysToCompute(input.substr(i + 1));
for (size_t r1 = 0; r1 < result1.size(); r1++){
for (size_t r2 = 0; r2 < result2.size(); r2++){
if (input[i] == '+'){
result.push_back(result1[r1] + result2[r2]);
}
else if (input[i] == '-'){
result.push_back(result1[r1] - result2[r2]);
}
else{
result.push_back(result1[r1] * result2[r2]);
}
}
}
}
}
if (result.empty() && !input.empty()){
result.push_back(stoi(input));
}
return result;
}
};