【LeetCode】22. Generate Parentheses (I thought I know Python...)

时间:2023-03-09 02:51:49
【LeetCode】22. Generate Parentheses (I thought I know Python...)

I thought I know Python...

Actually , I know nothing...

这个题真想让人背下来啊,每一句都很帅!!!

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

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

题意:找出n个括号的所有合法组合

在discuss区看到一个碾压级别的解法

https://discuss.leetcode.com/topic/17510/4-7-lines-python/13

 class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def g(p,left,right,res=[]):
if left:
g(p+'(',left-1,right)
if right>left:
g(p+')',left,right-1)
if not right:
res += p, #相当于res.append(p)
return res
return g('',n,n)

作者说他在这个题中用了几个tricks,我试着找了一下:

line15: 用return 语句启动内层嵌套的函数

line7:   res=[]给参数传递可变类型,为内层函数分配所有g函数副本可用的变量名

line13: 最后的逗号用的太神了,没有逗号的话结果完全错误,用逗号把p变为元组