码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode [241]Different Ways to Add Parentheses

时间:2019-05-09 21:46:23      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:java   code   不同   tput   ase   ||   case   group   方式   

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

标签:java   code   不同   tput   ase   ||   case   group   方式   

原文地址:https://www.cnblogs.com/xiaobaituyun/p/10841109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!