leetcode [241]Different Ways to Add Parentheses

Posted xiaobaituyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

题目大意:

给定一个字符串表达式,有不同的加括号的方式,使得最后计算得到的结果不同,得到所有不同结果的集合。

解法:

递归的将表达式按照运算符号分为两部分,然后再递归的求解两部分表达式的结果,并得到最后结果

java:

class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer>res=new ArrayList<>();
        for (int i=0;i<input.length();i++){
            if (input.charAt(i)==‘+‘|| input.charAt(i)==‘-‘||input.charAt(i)==‘*‘){
                List<Integer>part1=diffWaysToCompute(input.substring(0,i));
                List<Integer>part2=diffWaysToCompute(input.substring(i+1));
                for(int p1:part1){
                    for (int p2:part2){
                        int c=0;
                        switch (input.charAt(i)){
                            case ‘+‘:c=p1+p2;break;
                            case ‘-‘:c=p1-p2;break;
                            case ‘*‘:c=p1*p2;break;
                        }
                        res.add(c);
                    }
                }
            }
        }
        if (res.size()==0){
            res.add(Integer.parseInt(input));
        }

        return res;
    }
}

  

以上是关于leetcode [241]Different Ways to Add Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 241. Different Ways to Add Parentheses

leetcode 241. Different Ways to Add Parentheses (Python版)

leetcode 241. Different Ways to Add Parentheses

[LeetCode] 241. Different Ways to Add Parentheses

leetcode [241]Different Ways to Add Parentheses

LeetCode-241 Different Ways to Add Parentheses