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()
"(()())", "(())()", "()(())", "()()()"
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()
相关文章推荐
- 有关数据库SQL递归查询在不同数据库中的实现方法
- C#中的递归APS和CPS模式详解
- WinForm实现按名称递归查找控件的方法
- 使用SqlServer CTE递归查询处理树、图和层次结构
- C#中的尾递归与Continuation详解
- C#递归实现显示文件夹及所有文件并计算其大小的方法
- php递归创建目录的方法
- PHP递归创建多级目录
- Javascript递归打印Document层次关系实例分析
- shell中的各种括号的使用方法
- oracle 使用递归的性能提示测试对比
- 使用curl递归下载软件脚本分享
- Perl脚本实现递归遍历目录下的文件
- JavaScript的递归之递归与循环示例介绍
- C# 递归查找树状目录实现方法
- 全排列算法的非递归实现与递归实现的方法(C++)
- php递归列出所有文件和目录的代码
- java递归菜单树转换成pojo对象
- 一个JavaScript递归实现反转数组字符串的实例
- Java中的递归详解(用递归实现99乘法表来讲解)