22括號生成

題目描述

給出 n 代表生成括號的對數,請你寫出一個函數,使其能夠生成所有可能的並且有效的括號組合。

例如,給出 n = 3,生成結果爲:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

思路分析

  • 暴力解決:先生成所有序列,再對序列進行有效判斷。
  • 回溯:dfs+剪枝。

路徑:已經加入的左右括號。

選擇列表:還能加入的左右括號。

結束條件:左右括號數目各等於n;左括號數小於右括號數;左右括號數超出邊界。

代碼實現

    private List<String> list;

    public List<String> generateParenthesis(int n) {
        list = new ArrayList<>();
        process(0, 0, n, new StringBuffer());
        return list;
    }

    public void process(int ln, int rn, int n, StringBuffer str) {
        if (ln > n || rn > n || ln < rn) {
            return;
        }
 
        if (ln == n && rn == n) {
            list.add(str.toString());
        }

        process(++ln , rn, n, str.append("("));
        str.deleteCharAt(str.lastIndexOf("("));
        ln--;

        process(ln, ++rn , n, str.append(")"));
        str.deleteCharAt(str.lastIndexOf(")"));
        rn--;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章