zoukankan      html  css  js  c++  java
  • [Leetcode][Python]22: Generate Parentheses

    # -*- coding: utf8 -*-
    '''
    __author__ = 'dabay.wang@gmail.com'

    22: Generate Parentheses
    https://oj.leetcode.com/problems/generate-parentheses/

    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:
    "((()))", "(()())", "(())()", "()(())", "()()()"

    ===Comments by Dabay===
    递归。
    用left和right来记录剩余的左右括号数量。
    如果都不剩余了,把结果放入要返回的列表中。
    如果剩下的左括号比右括号多,说明不是合法的组合,返回。
    '''

    class Solution:
    # @param an integer
    # @return a list of string
    def generateParenthesis(self, n):
    def generateParenthesis2(left, right, string, res):
    if left == 0 and right == 0:
    res.append(string)
    return
    if left > right:
    return
    if left > 0:
    generateParenthesis2(left-1, right, string + "(", res)
    if right > 0:
    generateParenthesis2(left, right-1, string + ")", res)

    res = []
    generateParenthesis2(n, n, "", res)
    return res


    def main():
    sol = Solution()
    print sol.generateParenthesis(4)


    if __name__ == '__main__':
    import time
    start = time.clock()
    main()
    print "%s sec" % (time.clock() - start)
  • 相关阅读:
    查看kafka版本号
    This service allows sftp connections only. 解法
    raid5和raid10的异同
    mpstat命令
    力扣 2020.06.27
    力扣 2020.06.22
    windows10 LTSC 2019 激活
    shell 不等式的表示方法
    C#后台判断一个网站的有效性代码
    C#去除DataTable中的重复数值
  • 原文地址:https://www.cnblogs.com/Dabay/p/4254099.html
Copyright © 2011-2022 走看看