LeetCode 22. 括号生成(Generate Parentheses)
发布日期:2021-06-29 17:11:03 浏览次数:2 分类:技术文章

本文共 911 字,大约阅读时间需要 3 分钟。

16846478-fe604c1d3280ca45.jpg

LeetCode.jpg

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

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

[

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

Python3实现

递归

# @author:leacoder # @des:   递归 括号生成  class Solution:    def generateParenthesis(self, n: int) -> List[str]:        self.list = []        self.fnrecursive(0,0,n,"")        return self.list           #left:"("左括号被使用次数  right:")"右括号被使用次数 n:可以被使用括号对数  result:有效括号结果    def fnrecursive(self,left,right,n,result):        if left == n and right == n: # 左右括号使用次数均到达n次            self.list.append(result)            return        # 1、要使括号有效 ,那么我们最先放的是 左括号 ,需要满足left < n        if left < n:            self.fnrecursive(left+1,right,n,result + "(")        # 2、要使括号有效 ,右括号使用次数必然不大于左括号,并且 right < n        if left > right and right < n:             self.fnrecursive(left,right+1,n,result + ")")

GitHub链接:

知乎个人首页:
个人Blog:
欢迎大家来一起交流学习[图片上传中...(LeetCode.jpg-3f55e1-1554216352080-0)]

转载地址:https://blog.csdn.net/leacock1991/article/details/101467145 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 122. 买卖股票的最佳时机 II(Best Time to Buy and Sell Stock II)
下一篇:LeetCode 111. 二叉树的最小深度(Minimum Depth of Binary Tree)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月25日 07时06分46秒