leetcode(13)-括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses

用缓存

class Solution:
    def generateParenthesis(self, n: int):
        sets = {}
        def gen(n1,n2):
            if (n1,n2) in sets:
                return sets[n1,n2]
            ans = []
            if n1 ==2*n:
                return []
            else:
                leave = 2*n-n1
                if n2 <= leave-2:
                    res = gen(n1+1,n2+1)
                    ans.extend(['('+each for each in res])
                if n2>=1:
                    res = gen(n1+1,n2-1)
                    if res:
                        ans.extend([')'+each for each in res])
                    else:
                        ans = [')']
                sets[n1,n2] = ans
                return ans
        return gen(0,0)
#s = Solution()
#print(s.generateParenthesis(5))

闭合数如此简洁

class Solution(object):
    def generateParenthesis(self, N):
        if N == 0: return ['']
        ans = []
        for c in xrange(N):
            for left in self.generateParenthesis(c):
                for right in self.generateParenthesis(N-1-c):
                    ans.append('({}){}'.format(left, right))
        return ans

你可能感兴趣的:(leetcode(13)-括号生成)