Different Ways to Add Parentheses
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 (2-(1-1)) = 2
Output: [0, 2]
Example 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]
按照符号分成左边和右边,分别计算左右的结果,结果是一个数组,其中包含了左边或右边的所有情况。
然后全排列这些组合,就是当前所有的结果。
举例来说,"2-1-1":
第一个"-"计算了2 - (1 - 1),
第二个"-"计算了(2 - 1) - 1。
1 /** 2 * @param {string} input 3 * @return {number[]} 4 */ 5 var diffWaysToCompute = function(input) { 6 return compute(input); 7 8 function compute(str){ 9 var res = [], i, j, k, left, right; 10 if(!/+|-|*/.test(str)){ // + - * 11 return [parseInt(str)]; 12 } 13 for(i = 0 ; i < str.length; i++){ 14 if(/+|-|*/.test(str[i])){ // + - * 15 left = compute(str.substring(0, i)); 16 right = compute(str.substring(i + 1, str.length)); 17 for(j = 0; j < left.length; j++){ 18 for(k = 0; k < right.length; k++){ 19 if(str[i] === '+'){ 20 res.push(parseInt(left[j] + right[k])); 21 }else if (str[i] === '-'){ 22 res.push(parseInt(left[j] - right[k])); 23 }else if (str[i] === '*'){ 24 res.push(parseInt(left[j] * right[k])); 25 } 26 } 27 } 28 } 29 } 30 return res; 31 } 32 };