zoukankan      html  css  js  c++  java
  • [LeetCode] 241. 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"
    Output: [0, 2]
    Explanation: 
    ((2-1)-1) = 0 
    (2-(1-1)) = 2

    Example 2:

    Input: "2*3-4*5"
    Output: [-34, -14, -10, -10, 10]
    Explanation: 
    (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

    为运算表达式设计优先级。题意是给一个以字符串表示的运算表达式,请为其添加括号,展示出所有可能的解。运算符号只有+,-,*。

    思路是分治法。在实际操作的过程中,不需要真的添加括号,而是会通过分治的办法以达到括号能实现的运算优先级的目的。具体的思路是,遍历input字符串,每当遇到一个运算符号,就把这个符号的左边和右边分开,接着往下分治计算。在分治后的两个list中,挑出两个数字两两计算。最后把计算结果加入最后的list。

    时间 - ?

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<Integer> diffWaysToCompute(String input) {
     3         List<Integer> res = new ArrayList<>();
     4         for (int i = 0; i < input.length(); i++) {
     5             char c = input.charAt(i);
     6             if (c == '-' || c == '*' || c == '/') {
     7                 String a = input.substring(0, i);
     8                 String b = input.substring(i + 1);
     9                 List<Integer> aList = diffWaysToCompute(a);
    10                 List<Integer> bList = diffWaysToCompute(b);
    11                 for (int x : aList) {
    12                     for (int y : bList) {
    13                         if (c == '-') {
    14                             res.add(x - y);
    15                         } else if (c == '+') {
    16                             res.add(x + y);
    17                         } else if (c == '*') {
    18                             res.add(x * y);
    19                         }
    20                     }
    21                 }
    22             }
    23         }
    24         if (res.size() == 0) {
    25             res.add(Integer.valueOf(input));
    26         }
    27         return res;
    28     }
    29 }

    LeetCode 题目总结

  • 相关阅读:
    lnmp vhost 虚拟目录配置
    vi 编辑器常用命令(转)
    centos7 nginx 加入开机启动
    centos7 编译安装mysql
    IE8以下支持css3 border-radius渲染方法
    html5 web 摇一摇切换歌曲
    L0、L1与L2范数
    c++多线程编程:常见面试题
    核函数以及SVM相关知识(重点)
    梯度下降法的三种形式BGD、SGD以及MBGD
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13282852.html
Copyright © 2011-2022 走看看