括号生成问题

括号生成问题

1 min read

问题描述

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))

前一篇

悄无声息

后一篇

ZigZag Conversion(Z型字符串转换)