leetcode 22. 括号生成(python)

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:https://leetcode-cn.com/problems/generate-parentheses/solution/zui-jian-dan-yi-dong-de-dong-tai-gui-hua-bu-lun-da/

代码复现:

class Solution:
    def generateParenthesis(self, n: int):
        if n == 0:
            return []
        res = []
        res.append([None])
        res.append(["()"])
        for i in range(2, n + 1):
            tmp  = []
            for j in range(0, i):
                now_list1 = res[j]
                now_list2 = res[i - 1 - j]
                for k1 in now_list1:
                    for k2 in now_list2:
                        if k1 == None:
                            k1 = ""
                        if k2 == None:
                            k2 = ""
                        bracket = "(" + k1 +")" + k2
                        tmp.append(bracket)
            res.append(tmp)
        print(len(res), res)
        return res[n]

x = Solution()
print(x.generateParenthesis(3))

你可能感兴趣的:(leetcode,leetcode,python)