22. 生成括号

2020-01-30  本文已影响0人  oneoverzero

题目描述:

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

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

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

代码:

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = []
        self.backtrack(res, '', 0, 0, n)
        return res
    
    def backtrack(self, res=[], pth='', start=0, end=0, n=0):
        if end == n:
            res.append(pth)
            return
        if start < n:
            self.backtrack(res, pth+'(', start+1, end, n)
        if end < start:
            self.backtrack(res, pth+')', start, end+1, n)
上一篇 下一篇

猜你喜欢

热点阅读