#!/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-04-12 09:55:10 发布