您的位置:首页 > 其它

22. Generate Parentheses

2016-04-30 01:33 225 查看
题目: 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode 括号 递归