leetcode 22.括号生成(python3) 44ms

题目描述:

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

示例:

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

解题思路:

class Solution:
    def genParenthesis(self, a: int, b: int) -> List[str]:
        output = []
        if a == 0 and b == 1:
            output = [')']
            return output
        elif a == b:
            tmp = self.genParenthesis(a - 1, b)
            output = ['(' + string for string in tmp]
            return output
        elif a < b and a:
            tmpa = self.genParenthesis(a - 1, b)
            output = ['(' + string for string in tmpa]
            tmpb = self.genParenthesis(a, b - 1)
            output2 = [')' + string for string in tmpb]
            output.extend(output2)
            return output
        elif a ==0 and b > 1:
            tmp = self.genParenthesis(a, b - 1)
            output = [')' + string for string in tmp]
            return output
    def generateParenthesis(self, n: int) -> List[str]:
        if n == 0:
            return [""]
        a, b = n, n
        output = self.genParenthesis(a, b)
        return output

算法性能:
在这里插入图片描述

你可能感兴趣的:(leetcode)