zoukankan      html  css  js  c++  java
  • 【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变为元组

  • 相关阅读:
    Serilog 动态添加自定义属性
    C# 序列化与反序列化
    幂等设计
    服务无状态
    vue 显示 mysql 数据库表 Demo
    C# 调用 linux 函数 —— Linux 头文件目录位置
    创建可以在 Zynq 上运行的动态库
    C# 获取所在函数名
    Linux 关闭终端不结束进程
    C# 自动生成版本号
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6287729.html
Copyright © 2011-2022 走看看