1. 程式人生 > >LeetCode-Different Ways to Add Parentheses

LeetCode-Different Ways to Add Parentheses

一、Description

題目描述:給一個字串,任意加括號,輸出所有可能的取值。

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

二、Analyzation

每次遇到一個操作符,就通過遞迴找到左邊和右邊的字串對應的list,然後迴圈遍歷排列組合,add到list中。通過一個map可減少遞迴呼叫的時間。


三、Accepted code

class Solution {
    Map<String, List<Integer>> map = new HashMap<>();
    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> list = new ArrayList<>();
        if (null == input || 0 == input.length()) {
            return list;
        }
        if (map.containsKey(input)) {
            return map.get(input);
        }
        boolean flag = true;
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '+' || c == '-' || c == '*') {
                flag = false;
                List<Integer> left = diffWaysToCompute(input.substring(0, i));
                List<Integer> right = diffWaysToCompute(input.substring(i + 1, input.length()));
                for (int l : left) {
                    for (int r : right) {
                        if (c == '+') {
                            list.add(l + r);
                        } else if (c == '-') {
                            list.add(l - r);
                        } else {
                            list.add(l * r);
                        }
                    }
                }
            }
        }
        if (flag) {
            list.add(Integer.valueOf(input));
        }
        map.put(input, list);
        return list;
    }
}