generate parentheses
思路:递归,def generateRec(n, diff, res, solutions): n: 待生成的左右括号组,diff:左右括号的个数差,遵循单向recursion的基本模式即可
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def generateRec(n, diff, res, solutions):
if diff==0 and n==0:
solutions.append(''.join(res))
return
if diff<0:
return
if n>0:
res.append('(')
generateRec(n-1, diff+1, res, solutions)
res.pop()
res.append(')')
generateRec(n, diff-1, res, solutions)
res.pop()
res = []
solutions = []
generateRec(n, 0, res, solutions)
return solutions