1. 程式人生 > 實用技巧 >[LeetCode] 22. 括號生成

[LeetCode] 22. 括號生成

目錄


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

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

分析

  • 遞迴

解法

  • 根據剩餘的左括號、右括號數量判斷可拼接的括號,遞迴出口為剩餘的左括號、右括號數量都為0

  • 時間複雜度O(\(\frac{4^n}{\sqrt{n}}\)),卡特蘭數

  • 空間複雜度O(\(\frac{4^n}{\sqrt{n}}\))

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

    // left、right分別為剩餘的左括號、右括號
    public void dfs(String str, int left, int right){
        // 剩餘左括號、右括號都為0時,結束遞迴
        if(left == 0 && right == 0){
            res.add(str);
            return;
        }
        // 剩餘左括號時,可以拼接左括號
        if(left > 0){
            dfs(str + "(", left - 1, right);
        }
        // 剩餘右括號更多時,可以拼接右括號
        if(right > left){
            dfs(str + ")", left, right - 1);
        }
    }
}

//class Test{
//    public static void main(String[] args) {
//        Solution test = new Solution();
//        System.out.println(test.generateParenthesis(3));
//    }
//}