給出一個整數n,實現一個函數生成n對小括號,n對小括號的左右括弧順序不限,但應該閉合。python
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.git
example 1github
For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ].
n=2
的狀況爲n=1
時的括號串()
中在縫隙位置再插入一個括號,如1(2)3
中1,2,3
位置。能夠用set
剔除重複元素。函數
遞歸解決,n=3
時爲在()()
和(())
中再插入一個括號。code
思路2來源自leetcode討論區,使用open記錄已經有多少左括號,若是n==0,將")" * open
閉合。orm
class Solution(object): def __init__(self): self.table = {1: ['()']} def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ if n == 1: return self.table[1] if n-1 in self.table.keys(): nset = set() n1set = self.table[n-1] for _, item in enumerate(n1set): for j in range(len(item)): nset.add(item[0:j] + '()' + item[j:]) self.table[n] = list(nset) return self.table[n] else: self.generateParenthesis(n-1) return self.generateParenthesis(n) def gen2(self, n, open=0): if n == 0: return [')'*open] if open == 0: return ['('+x for x in self.gen2(n-1, 1)] else: return [')'+x for x in self.gen2(n, open-1)] + ['('+x for x in self.gen2(n-1, open+1)]
本題以及其它leetcode題目代碼github地址: github地址遞歸