原题目:
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 *
.
Input: "2-1-1"
.
((2-1)-1) = 0 (2-(1-1)) = 2
Output: [0, 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> v;
bool unit = true;
for(int i=0; i<input.length(); i++)
{
if(input[i] < '0' || input[i] > '9' )
{
unit = false;
vector<int> v1 = diffWaysToCompute(input.substr(0, i));
vector<int> v2 = diffWaysToCompute(input.substr(i+1, input.size()-i-1));
for(int j=0; j<v1.size(); j++)
for(int t=0; t<v2.size(); t++)
{
if(input[i]=='+') v.push_back(v1[j] + v2[t]);
else if(input[i]=='-') v.push_back(v1[j] - v2[t]);
else if(input[i]=='*') v.push_back(v1[j] * v2[t]);
}
}
}
if(unit) v.push_back(atoi(input.c_str()));
return v;
}
};