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变为元组

  • 相关阅读:
    面向对象的思维
    343. 整数拆分
    413. 等差数列划分
    303. 区域和检索
    62. 不同路径
    char类型与int类型相加
    mybatis里面resultmap的问题
    easyui的datagrid如何获取一个对象里面的成员对象里面的属性?
    ==和equls的区别
    泛型的使用思想
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6287729.html
Copyright © 2011-2022 走看看