问题描述
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example:
n = 3
output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
解题思路
使用递归的思想,生成n
对括号的有效组合,可以分解为一对括号()
,与n-1
对括号有效序列的组合。
例如:
n=1 output:['( )']
n=2 output:['( ) ( )','( ( ) )']
( ) ( )
↑ ↑
( ) ( )
n=3 output:['( ) ( ) ( )','( ( ) ) ( )','( ) ( ( ) )','( ( ( ) ) )', '( ( ) ( ) )']
( ) ( ) ( ) ( ) ( ) ( ) ( ( ) ) ( ( ) )
↑ ↑ ↑ ↑ ↑
( ) ( ) ( ) ( ) ( )
Python实现
class Solution:
def generateParenthesis(self, n):
if n == 1:
return ['()']
return self.combin('()',self.generateParenthesis(n-1))
def combin(self, ch, tgt):
res = []
for s in tgt:
for i in range(len(s)+1):
res.append(s[:i]+ch+s[i:])
return list(set(res))