题目:
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]
代码:
// 后根遍历
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> vec,leftVec,rightVec;
int i=0;
while(input[i]<='9'&& input[i]>='0') i++;
if(i==input.size()){// 只有一个叶子节点,返回这个数字
int num=0;
for(int j=0;j<i;++j)
num=num*10+input[j]-'0';
return {num};
}
// 比如 a*b-c+d,分别以'*','-','+'' 为根节点,构建二叉树
for(int i=0;i<input.size();++i){
while(input[i]>='0' && input[i]<='9') i++;// 找运算符
if(i==input.size()) break;
char opt=input[i];//运算符
leftVec=diffWaysToCompute(input.substr(0,i));
rightVec=diffWaysToCompute(input.substr(i+1,input.size()-i));
for(int j=0;j<leftVec.size();++j){
for(int k=0;k<rightVec.size();++k){
switch(opt){
case '+': vec.push_back(leftVec[j]+rightVec[k]);break;
case '-': vec.push_back(leftVec[j]-rightVec[k]);break;
case '*': vec.push_back(leftVec[j]*rightVec[k]);break;
}
}
}
}
return vec;
}
};