22.括号生成

Posted doona-jazen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了22.括号生成相关的知识,希望对你有一定的参考价值。

题目:

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses

分析:

题目刚拿到的时候确实没有思路,看了一下LeetCode的题解,注意到最后方法三的闭合数解法。

这里官方是采用了一个遍历回溯的思路,保证每一个添加的集合都是有效的,如何保证有效呢?当然是左右对称,那么就可以得到如下的代码:

技术图片
public static List<String> generateParenthesis(int n) {
    List<String> result = new ArrayList<String>();
    if (n == 0) {
        //结束回溯的关键
        result.add("");
    } else {
        for (int c = 0; c < n; ++c) {
            //遍历得到每一个需要添加的左右对称组合
            for (String left : generateParenthesis(c)) {
                for (String right : generateParenthesis(n - 1 - c)) {
                    //保证添加的左侧为对称的,右侧遍历而来,肯定也是对称的
                    result.add("(" + left + ")" + right);
                }
            }
        }
    }
    return result;
}
View Code

 

以上是关于22.括号生成的主要内容,如果未能解决你的问题,请参考以下文章

22. 括号生成

22. 括号生成

LeetCode 22. 括号生成c++/java详细题解

Leetcode22. 括号生成(简单回溯)

Leecode22. 括号生成——Leecode大厂热题100道系列

Leecode22. 括号生成——Leecode大厂热题100道系列