Topic Links:
Topic:
given A string of numbers and operators, return all possible results from computing all the different PO ssible 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]
Ideas:
Starting from left to right, the operator is treated as the center of the expression, and the expression is divided into two parts, recursively calculating the right and left parts, and the result is computed with the operator, and this calculation is equivalent to enclosing the operator with parentheses (a left Op right). Once each operator in the expression is done as above, the result value is obtained for all possible scenarios. To optimize time, you can use a HashMap to save the already calculated situation.
Algorithm:
Map<string, list<integer>> maps = new hashmap<string, list<integer>> (); Public list<integer> Diffwaystocompute (String input) {list<integer> results = new ARRAYLIST<INTEGER&G t; (); for (int i = 0; i < input.length (); i++) {Char t = input.charat (i); if (t = = ' + ' | | t = = '-' | | t = = ' * ') {String sleft = input.substring (0, I); String sright = input.substring (i + 1); List<integer> left, right; if (Maps.containskey (Sleft)) {left = Maps.get (Sleft); } else {left = Diffwaystocompute (input.substring (0, I));//All possible calculation results on the right side} if (Maps.containskey (Sright)) {right = Maps.get (sright); } else {right = Diffwaystocompute (input.substring (i + 1)); } for (int l:left) {for (int r:right) { int res = 0; Switch (t) {case ' + ': res = l + R; Break Case '-': res = l-r; Break Case ' * ': res = l * r; Break } results.add (res); }}}} if (results.size () = = 0) {//When input is a number Results.add (Integer.parseint (INP UT)); } return results; }
"Leetcode" Different Ways to ADD parentheses