1. 程式人生 > 其它 >LeetCode-22-括號生成

LeetCode-22-括號生成

題目

數字 n 代表生成括號的對數,請你設計一個函式,用於能夠生成所有可能的並且 有效的 括號組合。

輸入:n = 3
輸出:["((()))","(()())","(())()","()(())","()()()"]

思路

回溯 + 剪枝

  • 當前左右括號都有大於 0 個可以使用的時候,才產生分支;
  • 產生左分支的時候,只看當前是否還有左括號可以使用;
  • 產生右分支的時候,還受到左分支的限制,右邊剩餘可以使用的括號數量一定得在嚴格大於左邊剩餘的數量的時候,才可以產生分支;
  • 在左邊和右邊剩餘的括號數都等於 0 的時候結算

程式碼實現

public class Solution {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        dfs("", 0, 0, n, res);
        return res;
    }

    /**
     * @param curStr 當前遞迴得到的結果
     * @param left   左括號已經用了幾個
     * @param right  右括號已經用了幾個
     * @param n      左括號、右括號一共得用幾個
     * @param res    結果集
     */
    private void dfs(String curStr, int left, int right, int n, List<String> res) {
        if (left == n && right == n) {
            res.add(curStr);
            return;
        }
        // 剪枝
        if (left < right) {
            return;
        }
        if (left < n) {
            dfs(curStr + "(", left + 1, right, n, res);
        }
        if (right < n) {
            dfs(curStr + ")", left, right + 1, n, res);
        }
    }
}