[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; } };
相关文章推荐
- web开发的第一个小作品--html svg +css+js时钟效果
- (转)JavaScript 中对变量和函数声明的“提前(hoist)”
- JavaScript中双叹号“!!”作用
- js之节点属性
- JavaScript取出字符串和尾随空格
- 浏览器兼容处理(HTML条件注释、CSSHack和JS识别)
- XML 数据请求与JSON 数据请 4000 求
- JS之dom操作getAttribute()方法
- JS之dom操作getAttribute()方法
- TouchSlide.1.1.js 参数
- js事件知识整理
- Javascript学习笔记【第四章】
- JSP之response对象使用
- 深入分析JS原型链以及为什么不能在原型链上使用对象
- 浅谈 Underscorejs中 _.throttle 和 _.debounce 的差异和使用场景
- JavaScript的函数作用域与作用域链详解
- javaScript简单教程之一
- javascript中的原型链,prototype与__proto__的关系
- Underscore.js使用
- mobilebone.js使用笔记