1. 程式人生 > 其它 >LeetCode22 括號生成

LeetCode22 括號生成

題目

數字 n代表生成括號的對數,請你設計一個函式,用於能夠生成所有可能的並且 有效的 括號組合。
有效括號組合需滿足:左括號必須以正確的順序閉合。

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

示例 2:
輸入:n = 1
輸出:["()"]

提示:
1 <= n <= 8

方法

方法1:回溯法

  • 時間複雜度:O()
  • 空間複雜度:O()
class Solution {
    private List<String> result = new ArrayList<>();
    private StringBuffer temp = new StringBuffer();
    public List<String> generateParenthesis(int n) {
        if(n<1){
            return result;
        }
        dfs(n,0,0,0);
        return result;
    }
    private void dfs(int n,int depth,int open,int close){
        if(depth==n*2){
            result.add(temp.toString());
            return;
        }
        if(open<n){
            temp.append("(");
            dfs(n,depth+1,open+1,close);
            temp.deleteCharAt(temp.length()-1);
        }
        if(close<open){
            temp.append(")");
            dfs(n,depth+1,open,close+1);
            temp.deleteCharAt(temp.length()-1);
        }
    }
}

方法2: