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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
这题其实是一道动态规划题,我们可以把它想象成一个生成括号的过程,分别用o和c记录左括号和右括号的数量。在任何情况下都要保证c不大于o。跳出的判断是o=c=n。现在看递归里,判断o是否小于等于n,超过n的时候直接return到上一层。因为探索的过程中始终都要o<=c,如果右括号多了那么不匹配。所以我们先递归到o+1,加一个左括号。什么时候可以加右括号,当o>c的时候,有左括号可以和右括号匹配了,这时才能递归到加右括号。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans=[]
def dfs(o,c,s):
if o==n and c==n:
ans.append(s)
if o<=n:
dfs(o+1,c,s+'(')
if o>c:
dfs(o,c+1,s+')')
return
dfs(0,0,'')
return ans