您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Different Ways to Add Parentheses

2015-09-20 17:23 295 查看

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]


https://leetcode.com/problems/different-ways-to-add-parentheses/

按照符号分成左边和右边,分别计算左右的结果,结果是一个数组,其中包含了左边或右边的所有情况。
然后全排列这些组合,就是当前所有的结果。
举例来说,"2-1-1":
第一个"-"计算了2 - (1 - 1),
第二个"-"计算了(2 - 1) - 1。

/**
* @param {string} input
* @return {number[]}
*/
var diffWaysToCompute = function(input) {
return compute(input);

function compute(str){
var res = [], i, j, k, left, right;
if(!/\+|\-|\*/.test(str)){ // + - *
return [parseInt(str)];
}
for(i = 0 ; i < str.length; i++){
if(/\+|\-|\*/.test(str[i])){ // + - *
left = compute(str.substring(0, i));
right = compute(str.substring(i + 1, str.length));
for(j = 0; j < left.length; j++){
for(k = 0; k < right.length; k++){
if(str[i] === '+'){
res.push(parseInt(left[j] + right[k]));
}else if (str[i] === '-'){
res.push(parseInt(left[j] - right[k]));
}else if (str[i] === '*'){
res.push(parseInt(left[j] * right[k]));
}
}
}
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: