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--;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章