题目:
22. Generate Parentheses
Medium
5731287Add to ListShare
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
题意:
给定n,要输出n个左括号和右括号能匹配的所有字符串。
思路:
回溯法。推荐回溯法讲解文章:https://segmentfault.com/a/1190000006121957 (讲的很好)
感谢博客:https://blog.csdn.net/fuxuemingzhu/article/details/79362373(分析得很好)
--------------------------------------------------------------------------------------------------------------------------
回溯法是一个剪枝了的二叉树。我们要得到的结果是可以good leaf,如果不满足good leaf就继续向下搜索,搜索的时候需要满足一定的条件。
从上面的图片中我们可以很明显的看到,最后五条画黑线的就是最终的结果,其中左分支都是添加左括号,又分支都是添加右括号。
那么我们在什么情况下添加左括号呢?很明显,最多能添加 n 个左括号,在递归调用的时候,在能传递到最底层的共用字符串中先添加 ”(“ ,然后 left-1,递归调用就可以。
那什么时候添加右括号呢?当左括号个数大于右括号的个数时添加右括号。
总之,向下搜索要满足两个条件:
- 左括号插入数量不超过n,也即左括号剩余可插数量left>0
- 可以插入
)
的前提是(
左括号的数量大于大于右括号),也即左括号剩余可插数量小于右括号可插数量,left<right
代码:
####22回溯
# https://segmentfault.com/a/1190000006121957(回溯详解)
#https://blog.csdn.net/fuxuemingzhu/article/details/79362373
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
path = ''
self.dfs(res,n,n,path)
return res
#左括号插入条件:最多n个,即剩余括号数大于0个
#右括号插入条件:左括号数大于右括号数,即左括号剩余数小于右括号剩余数
def dfs(self,res,left,right,path):
if left == 0 and right==0:
res.append(path)
return
if left>0:
self.dfs(res,left-1,right,path+'(')
if left<right:
self.dfs(res,left,right-1,path+')')