[LeetCode] 22. 括号生成

题目链接:https://leetcode-cn.com/problems/generate-parentheses/

题目描述:

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

示例:

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

思路:

回溯算法

递归过程中,通过左括号和右括号的个数判断是否还可以组成有效的括号的组合


关注我的知乎专栏,了解更多的解题技巧!

代码:

python

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        
        def helper(left_p, right_p, tmp):
            if left_p == 0 and right_p == 0:
                res.append(tmp)
                return
            if left_p < 0 or right_p < 0 or left_p > right_p:
                return 
            helper(left_p-1, right_p, tmp+"(")
            helper(left_p, right_p-1, tmp+")")
        helper(n, n, "")
        return res

java

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

    }

    public void backtrack(ArrayList<String> res, String s, int left_p, int right_p) {
        if (left_p == 0 && right_p == 0) {
            res.add(s);
            return;
        }
        if (left_p < 0 || right_p < 0 || left_p > right_p) return;
        backtrack(res,s+"(",left_p-1,right_p);
        backtrack(res,s+")",left_p,right_p-1);
    }
}
原文地址:https://www.cnblogs.com/powercai/p/10775179.html