题目描述
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]
解题思路
题目大致含义就是在计算表达式上加括号,以此决定最终的计算优先级和结果,最后返回所有计算结果构成的数组,顺序不限。
本题是一个典型的动态规划问题,因为最终解可以由子问题的解组合得到,我们观察要求的数组,对于每一种运算,其左右两侧的问题类型与要求的问题类型相同,组合左右两侧的结果,就可以得到最终结果,其状态转移方程可以用如下递归式表达:
s[i] =s(i) “+/-/*” s(i+1);
只需扫描一遍输入序列,即可得到解。
代码如下:
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
for(int i = 0; i<input.size();++i) {
char iChar = input[i];
if(iChar == '+' || iChar == '-' || iChar == '*') {
auto vec1 = diffWaysToCompute(input.substr(0,i));
auto vec2 = diffWaysToCompute(input.substr(i+1));
for(auto val1:vec1)
for(auto val2:vec2) {
if(iChar == '+')
result.push_back(val1+val2);
if(iChar == '-')
result.push_back(val1-val2);
if(iChar == '*')
result.push_back(val1*val2);
}
}
}
if(result.empty())
result.push_back(stoi(input));
return result;
}
};