题目: 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: "((()))", "(()())", "(())()", "()(())", "()()()"
Python:
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
nl = n; nr = n; curstr=[];result=[]
self.helper(nl,nr,curstr,result)
return result
def helper(self,nl,nr,curstr,result):
if nl==0 and nr==0:
result.append(''.join(curstr))
return
elif nl>nr or nl<0 or nr<0:
return
else:
curstr.append('(')
nl-=1
self.helper(nl,nr,curstr,result)
curstr.pop()
nl+=1
curstr.append(')')
nr-=1
self.helper(nl,nr,curstr,result)
curstr.pop()