#!/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:
[ "((()))",
"(()())",
"(())()",
"()(())",
"()()()"]
'''classSolution(object):defgenerateParenthesis(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
deffun(self,tmp,result,left,right,index):if left == 0and right == 0:
result.append(''.join(tmp))
if left > 0: #只要有(,就能放
tmp[index] = '('
self.fun(tmp,result,left - 1,right,index + 1)
if right > 0and left < right:#(放了,)才能放,保证有一个(与之配对if left == 0: #小优化....for i in range(right):
tmp[index + i] = ')'
result.append(''.join(tmp))
return0
tmp[index] = ')'
self.fun(tmp,result,left,right - 1,index + 1)
if __name__ == "__main__":
s = Solution()
print s.generateParenthesis(3)