zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Different Ways to Add Parentheses

    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。
     
     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 };
     
     
     
  • 相关阅读:
    C# comboBox实现省市两级联动(winform)
    Alter用法
    封装SQLHelper
    杨中科版C#射击游戏
    C# TXT文件导入至数据库
    C# 手机号码归属地查询
    C#中从数据库导出至txt
    解决C#中txt文档导入数据库时,中文显示乱码的问题
    第一篇博文与技术无关 纯瞎扯
    全国省市数据库
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4823785.html
Copyright © 2011-2022 走看看