#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
举例:
given n = 3, a solution set is:
[ "((()))",
"(()())",
"(())()",
"()(())",
"()()()"]
'''
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n < 1:
return []
result = []
tmp = ['('] * n * 2
left = n - 1
right = n
#第一个一定要为(
self.fun(tmp,result,left,right,1)
return result
def fun(self,tmp,result,left,right,index):
if left == 0 and right == 0:
result.append(''.join(tmp))
if left > 0: #只要有(,就能放
tmp[index] = '('
self.fun(tmp,result,left - 1,right,index + 1)
if right > 0 and left < right:#(放了,)才能放,保证有一个(与之配对
if left == 0: #小优化....
for i in range(right):
tmp[index + i] = ')'
result.append(''.join(tmp))
return 0
tmp[index] = ')'
self.fun(tmp,result,left,right - 1,index + 1)
if __name__ == "__main__":
s = Solution()
print s.generateParenthesis(3)
23 leetcode - Generate Parentheses
最新推荐文章于 2025-12-15 23:25:39 发布
本文介绍了一个使用递归方法生成合法括号组合的Python程序。给定一个正整数n,该程序能生成所有可能的由n对括号组成的合法字符串。合法字符串要求每个左括号必须有对应的右括号闭合。
166

被折叠的 条评论
为什么被折叠?



