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> res;
for(int i=0;i<input.size();i++)
{
if(input[i]=='+'||input[i]=='-'||input[i]=='*')
{
vector<int> left=diffWaysToCompute(input.substr(0,i));
vector<int> right=diffWaysToCompute(input.substr(i+1));
for(int j=0;j<left.size();j++)
{
for(int k=0;k<right.size();k++)
{
if(input[i]=='+'){res.push_back(left[j]+right[k]); }
if(input[i]=='-'){res.push_back(left[j]-right[k]); }
if(input[i]=='*'){res.push_back(left[j]*right[k]); }
}
}
}
}
if(res.empty()) res.push_back(atoi(input.c_str()));
return res;
}
};
第二次做没有自己做出来,附加了一些解释在下面
class Solution {
public:
vector<int> result;
vector<int> diffWaysToCompute(string input) {
if(input.empty()) return result;
result=solve(input);
return result;
}
vector<int> solve(string str){
vector<int> res;
//if(str.empty()) return res;//因为符号左边或者右边不可能是空的,所以没有必要用这条语句
for(int i=0;i<str.size();i++){
if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/'){
vector<int> left=solve(str.substr(0,i));//left里存的是以当前符号为分割位的左边string中各种可能解法的结果,各种结果是互斥的
vector<int> right=solve(str.substr(i+1));//右边string的各种结果
for(int j=0;j<left.size();j++){
for(int k=0;k<right.size();k++){
switch(str[i]) {
case '+':res.push_back(left[j]+right[k]) ;break;
case '-':res.push_back(left[j]-right[k]) ;break;
case '*':res.push_back(left[j]*right[k]) ;break;
case '/':res.push_back(left[j]/right[k]) ;break;
}
}
}
}
}
if(res.empty()) res.push_back(stoi(str));
return res;
}
};