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]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
1 Public classSolution {2 PublicList<integer>diffwaystocompute (String input) {3list<integer> ans =NewArraylist<integer>();4 for(inti = 0; I < input.length (); i++){5 Charc =Input.charat (i);6 if(c! = ' + ' && c! = '-' && c! = ' * ')Continue;7List<integer> left = Diffwaystocompute (input.substring (0, i));8List<integer> right = Diffwaystocompute (input.substring (i+1, Input.length ()));9 for(intle:left) {Ten for(intri:right) { One if(c = = ' + ') Ans.add (le+RI); A Else if(c = = '-') Ans.add (le-RI); - Else if(c = = ' * ') Ans.add (le*RI); - } the } - } - if(ans.size () = = 0) Ans.add (Integer.parseint (input)); - returnans; + } -}
The idea of using divide and conquer.
241. Different Ways to ADD parentheses Java solutions