Topic:
Given A string of numbers and operators, return all possible results from computing all the different possible ways to Gro Up 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]
Ideas:
1. When you see the problem of the idea: the operator and the two sides of the number bracket as a whole, recursive completion of the parentheses .... I don't know how to write code like this.
2. Refer to Gcdofree method: Divide and conquer the method, recursive completion, this idea is better
3. Dynamic planning: This is still not understood, and so on later to add
Code: C + + ideas 2
classSolution { Public: Vector<int> Diffwaystocompute (stringinput) {Vector<int>solution; for(inti =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(intj =0; J < Left.size (); J + +) { for(intK =0; K < Right.size (); k++) { if(Input[i] = ='+') Solution.push_back (Left[j]+Right[k]); Else if(Input[i] = ='-') Solution.push_back (Left[j]-Right[k]); Elsesolution.push_back (Left[j]*Right[k]); } } } } if(Solution.empty ()) Solution.push_back (Stoi (input)); returnsolution; }};
Leetcode 241. Different Ways to Add parentheses