LeetCode 22. 括号生成

22. 括号生成

Difficulty: 中等

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1
输出:["()"]

提示:

  • 1 <= n <= 8

Solution

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []
        self.helper('', n, n, res)
        return res
        
    def helper(self, curr, l, r, res):
        # 如果左括号和右括号的数量都为0,直接返回        
        if l == 0 and r == 0:
            res.append(curr)
            return
        if l > 0:  # 添加左括号:左括号剩余的数量大于0
            self.helper(curr + '(', l-1, r, res)
        if r > l:  # 添加右括号:左括号剩余的数量小于右括号剩余的数量
            self.helper(curr + ')', l, r-1, res)
原文地址:https://www.cnblogs.com/swordspoet/p/14363730.html