【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

 1 class Solution(object):
 2     def generateParenthesis(self, n):
 3         """
 4         :type n: int
 5         :rtype: List[str]
 6         """
 7         def g(p,left,right,res=[]):
 8             if left:
 9                 g(p+'(',left-1,right)
10             if right>left:
11                 g(p+')',left,right-1)
12             if not right:
13                 res += p,                   #相当于res.append(p)
14             return res
15         return g('',n,n)

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

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

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

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

原文地址:https://www.cnblogs.com/fcyworld/p/6287729.html