241. Different Ways to Add Parentheses

来源:互联网 发布:淘宝店铺域名太长了 编辑:程序博客网 时间:2024/05/31 04:03

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]

思路:就是一个递归求和的问题,有点归并的感觉

代码如下(已通过leetcode)

public class Solution {
   public List<Integer> diffWaysToCompute(String input) {
       List<Integer> list=new ArrayList<Integer>();
       if(input==null ||input.length()==0) return list;
       if(!input.contains("+")&&!input.contains("-")&&!input.contains("*")) {
        list.add(Integer.valueOf(input));
        return list;
       }
       for(int i=0;i<input.length();i++) {
        char ops=input.charAt(i);
        if(ops=='+'||ops=='-'||ops=='*') {
        List<Integer> left=diffWaysToCompute(input.substring(0,i));
        List<Integer> right=diffWaysToCompute(input.substring(i+1,input.length()));
        for(int leftvalue:left) {
        for(int rightvalue:right) {
        switch(ops) {
        case '+': list.add(leftvalue+rightvalue);
        break;
        case '-': list.add(leftvalue-rightvalue);
    break;
        case '*': list.add(leftvalue*rightvalue);
    break;
       
        }
        }
        }
       
        }
       
       }
       return list;
   }
}

0 0
原创粉丝点击