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”
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:

Input: “23-45”
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(45))) = -34
((2
3)-(45)) = -14
((2
(3-4))5) = -10
(2
((3-4)5)) = -10
(((2
3)-4)*5) = 10
代码:
类似归并排序算法

class Solution {
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> way = new ArrayList<>();
        for(int i=0; i<input.length(); i++){
            char c = input.charAt(i);
            if(c=='+' || c=='-' ||c=='*'){
                List<Integer> left = diffWaysToCompute(input.substring(0,i));
                List<Integer> right = diffWaysToCompute(input.substring(i+1));
                for(int l:left){
                    for(int r:right){
                        switch(c){
                            case '+':
                                way.add(l+r);
                                break;
                            case '-':
                                way.add(l-r);
                                break;
                            case '*':
                                way.add(l*r);
                                break;
                        }
                    }
                }
            }
        }
        if(way.size()==0){
            way.add(Integer.valueOf(input));
        }
        return way;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/88604976