[leetcode: Python]22. Generate Parentheses
来源:互联网 发布:服装数据分析公式 编辑:程序博客网 时间:2024/05/22 15:59
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
解题思路:列举出所有合法的括号匹配,使用dfs。如果左括号的数量大于右括号的数量的话,就不能产生合法的括号匹配。
方法一:65ms
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def generate(p, left, right): if right >= left >= 0: if not right: yield p for q in generate(p + '(', left - 1, right) : yield q for q in generate(p + ')', left, right - 1) : yield q return list(generate('', n, n))
方法二:55ms
class Solution(object): def deep(self,tot,ln,rn,strs,lis): if ln<tot: self.deep(tot,ln+1,rn,strs+'(',lis) if rn<tot and rn<ln: self.deep(tot,ln,rn+1,strs+')',lis) if ln==tot and rn==tot: lis.append(strs) def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ lis=[] self.deep(n,0,0,'',lis) return lis
方法三:45ms
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def genrate(p,left,right,parens=[]): if left: genrate(p+ '(',left-1,right) if right>left: genrate(p+')',left,right-1) if not right: parens+=p, return parens return genrate('',n, n)
方法四:39ms
这个没了解
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ mp = [[""], ["()"]] for i in xrange(2, n + 1): mp.append([]) for j in xrange(i): for x in mp[j]: for y in mp[i - 1 - j]: mp[i].append("(" + x + ")" + y) return mp[-1]
阅读全文
0 0
- [leetcode: Python]22. Generate Parentheses
- 【Leetcode】【python】Generate Parentheses
- [LeetCode]22.Generate Parentheses
- LeetCode --- 22. Generate Parentheses
- LeetCode 22.Generate Parentheses
- [Leetcode] 22. Generate Parentheses
- 【LeetCode】22.Generate Parentheses
- [leetcode] 22.Generate Parentheses
- 【leetcode】22. Generate Parentheses
- Leetcode-22.Generate Parentheses
- [leetcode] 22. Generate Parentheses
- 22. Generate Parentheses LeetCode
- leetcode 22. Generate Parentheses
- [LeetCode]22. Generate Parentheses
- leetcode 22. Generate Parentheses
- leetcode 22. Generate Parentheses
- LeetCode 22. Generate Parentheses
- [LeetCode]22. Generate Parentheses
- (HDU 6024 女生专场)Building Shops 简单DP详细解答
- unity之屏幕截图
- bzoj 1083 繁忙的都市(瓶颈生成树)
- 网页打开pdf文件屏蔽打印保存解决方案
- j2ee的web项目,并发是什么意思,举个例子。
- [leetcode: Python]22. Generate Parentheses
- 更换MyEclipse的默认jdk
- 指针
- webx解决csrf漏洞
- layui-登陆
- Nslog格式汇总
- Struts2 annoatation Inteceptor(拦截器)
- Leetcode 66. Plus One
- Java继承如何实现