1. 程式人生 > >[leetcode]22. Generate Parentheses

[leetcode]22. Generate Parentheses

Solution 1: 遞歸回溯法

回溯就是找到所有的解,一直沒用java寫過回溯,突然有點懵逼

一直往左下走

if (open < max)
            backtrack(ans, cur+"(", open+1, close, max);

cur還是左下之前的值,再繼續往右下走

 if (close < open)
            backtrack(ans, cur+")", open, close+1, max);

這個類似與0-1揹包問題,時間複雜度是0(2的h(n)次方),其中h(n)是一條路徑的長度,在這一題就是2n。所以時間複雜度是2的2

n次方也就是O(4的n次方)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList();
        backtrack(ans, "", 0, 0, n);
        return ans;
    }

    public void backtrack(List<String> ans, String cur, int open, int close, int max){
        if (cur.length() == max * 2) {
            ans.add(cur);
            return;
        }

        if (open < max)
            backtrack(ans, cur+"(", open+1, close, max);
        if (close < open)
            backtrack(ans, cur+")", open, close+1, max);
    }
}

Solution 2: 巧妙的遞迴

其中left和right都是有效的string

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList();
        if (n == 0) {
            ans.add("");
        } else {
            for (int c = 0; c < n; ++c)
                for (String left: generateParenthesis(c))
                    for (String right: generateParenthesis(n-1-c))
                        ans.add("(" + left + ")" + right);
        }
        return ans;
    }
}