zoukankan      html  css  js  c++  java
  • Leetcode: 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]

    用到了Divide and Conquer, 跟 Leetcode: Unique Binary Search Trees II 很像

    在input string里遍历各个operator, 依据每个operator分成左右子串,左右子串做递归返回所有可能的results,然后全排列。

    注意很巧妙的一点在于寻找operator来划分,然后如果像20-23行那样没有划分成功(因为每找到operator)则Inter.parseInt(input),这样省去了计算多位integer的工夫。比如input.charAt(i)=2, input.charAt(i+1)=3, 我们不需要再自己计算得到23. 

     1 public class Solution {
     2     public List<Integer> diffWaysToCompute(String input) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         if (input==null || input.length()==0) return res;
     5         
     6         for (int i=0; i<input.length(); i++) {
     7             char c = input.charAt(i);
     8             if (!isOperator(c)) continue;
     9             List<Integer> left = diffWaysToCompute(input.substring(0, i));
    10             List<Integer> right = diffWaysToCompute(input.substring(i+1));
    11             for (int j=0; j<left.size(); j++) {
    12                 for (int k=0; k<right.size(); k++) {
    13                     int a = left.get(j);
    14                     int b = right.get(k);
    15                     res.add(calc(a,b,c));
    16                 }
    17             }
    18         }
    19         
    20         if (res.size() == 0) { //input is not null or size==0, but res.size()==0, meaning input is just a number
    21             res.add(Integer.parseInt(input));
    22         }
    23         return res;
    24     }
    25     
    26     public boolean isOperator(char c) {
    27         if (c=='+' || c=='-' || c=='*') return true;
    28         return false;
    29     }
    30     
    31     public int calc(int a, int b, char c) {
    32         int res = Integer.MAX_VALUE;
    33         switch(c) {
    34             case '+': res = a+b; break;
    35             case '-': res = a-b; break;
    36             case '*': res = a*b; break;
    37         }
    38         return res;
    39     }
    40 }
  • 相关阅读:
    Http Get与Post的区别
    华为USG6000V防火墙简单配置案例
    华为USG6000V防火墙简单配置案例
    基于三层交换机的VRRP技术--MSTP、VRRP的综合运用
    ci test
    CI框架 default_controller 如何设置为:'目录/Controller' 转
    查看django版本的方法
    Django如何安装指定版本
    django学习--2 模板
    django学习--1
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5068637.html
Copyright © 2011-2022 走看看