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 ((1-1)) = 2
Output:[0, 2]
Example 2
Input:"2*3-4*5"
((4*5)) =-34 ((2*3)-(4*5)) = 14 ((3-4)) = 10 (((3-4))) =-10 (((2*3) 4) = 10
Output:[-34, -14, -10, -10, 10]
The main idea here is that the left and right sub-strings are calculated separately, then do the whole arrangement on the line, there may be a very repetitive calculation so that the efficiency is lower
1 classSolution {2 Public:3vector<int> Diffwaystocompute (stringinput) {4vector<int>result;5 intLength =input.length ();6 for(inti =0; i < length; ++i) {7 Charc =Input[i];8 if(c = ='+'|| c = ='-'|| c = ='*'){9 stringInputleft = Input.substr (0, i);Ten stringInputright = Input.substr (i+1); Onevector<int>leftresult =Diffwaystocompute (inputleft); Avector<int>rightresult =Diffwaystocompute (inputright); - for(intj =0; J < Leftresult.size (); ++j) { - for(intK =0; K < Rightresult.size (); ++k) { the if(c = ='+') -Result.push_back (Leftresult[j] +rightresult[k]); - Else if(c = ='-') -Result.push_back (Leftresult[j]-rightresult[k]); + Else if(c = ='*') -Result.push_back (Leftresult[j] *rightresult[k]); + } A } at } - } - if(Result.empty ())//The main function of this step is to tell the final character of the divide to be converted into numbers - result.push_back (Stoi (input)); - returnresult; - } in};
Leetcode oj:different Ways to add parentheses (method of adding parentheses in different locations)