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"
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(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
根据题意,找出所有可能的运算顺序,并输出对应的结果。
在这里可以用分治的思想。若要求对于给定的长度为 n 的string输入,可以先退而求其次,求出给定输入的子列的所有可能的情况。并将子列长度为 1 或 2 时作为最小自问题(不可分割的基本问题)。根据这一指导思想进行程序设计。
首先,将运算符作为分割string的标志,划分为左右两部分。执行递归时应当注意,一个子序列的很可能有很多种,据此,设定递归函数的返回值为数组。合并左右两部分可能的结果时,再按照操作运算计算出所有的结果,即当前递归区间的所有可能
class Solution {
private:
vector<int> divide(int lo,int hi,string& input){
vector<int> storeSum;
for(register int i=lo;i<=hi;i++)
if(input[i]=='+' || input[i]=='-' || input[i]=='*'){
vector<int> leftSum=divide(lo,i-1,input);
vector<int> rightSum=divide(i+1,hi,input);
for(auto eleL : leftSum)
for(auto eleR : rightSum){
switch(input[i]){
case '+':
storeSum.push_back(eleL+eleR);
break;
case '-':
storeSum.push_back(eleL-eleR);
break;
case '*':
storeSum.push_back(eleL*eleR);
break;
}
}
}
if(storeSum.size()==0){
int num=0;
for(register int i=lo;i<=hi;i++)
num=num*10+input[i]-'0';
storeSum.push_back(num);
}
return storeSum;
}
public:
vector<int> diffWaysToCompute(string input) {
vector<int> ans;
if(input.size()==0)
return ans;
ans=divide(0,input.size()-1,input);
return ans;
}
};
在递归中,不难发现许多区间是重复计算的,因此可以借助map<string,vector< int> >来优化程序
这个暂时没有代码 qwq