leetcode Generate Parentheses python

时间:2021-07-28 03:10:34
# 解题思路:列举出所有合法的括号匹配,使用dfs。如果左括号的数量大于右括号的数量的话,就不能产生合法的括号匹配
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 0:
return []
res = []
self.recursion(n,n,'',res)
return res
def recursion(self,left,right,item,res):
if right < left:
return
if left == 0 and right == 0:
res.append(item)
if left > 0:
self.recursion(left-1,right,item+'(',res)
if right > 0:
self.recursion(left,right-1,item+')',res)

@link http://www.cnblogs.com/zuoyuan/p/3779797.html