241. Different Ways to Add Parentheses

Problem:
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
Analysis:
Divide and conquer. The total result is the Cartesian set of sub results. If we divide a "+" operator, get left result [10,20,30] right result [3,6,8]. Then we will have 3*3 = 9 different results.

Solution:
The current input is number is when there is no divide, the temp result size is zero.

class Solution {
    Map<String, List<Integer>> map = new HashMap<>();
    public List<Integer> diffWaysToCompute(String input) {
        if (map.containsKey(input)) {
            return map.get(input);
        }
        List<Integer> res = new ArrayList<>();
        if (input == null || input.length() == 0)
            return res;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '-' || c == '+' || c == '*') {
                List<Integer> res1 = diffWaysToCompute(input.substring(0, i));
                List<Integer> res2 = diffWaysToCompute(input.substring(i + 1));
                for (int n1 : res1) {
                    for (int n2: res2) {
                        if (c == '+') {
                            res.add(n1 + n2);
                        } else if (c == '-') {
                            res.add(n1 - n2);
                        } else if (c == '*') {
                            res.add(n1 * n2);
                        }
                    }
                }
            }
        }
        
        if (res.size() == 0)
            res.add(Integer.valueOf(input));
        map.put(input, res);
        return res;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List