zoukankan      html  css  js  c++  java
  • 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:

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

    这题的核心在于如何约束保证最后的结果符合well-formed要求。本质而言如果我们用一个栈模拟,则每次添加一个‘(’,则入栈一个‘)’。栈空则无法加‘)’。否则可以加‘)’。也就是每一步都必须要保证‘(’的数目大于等于‘)’。最后‘(’和‘)’的数目都等于n。用l,r分别表示还需要添加的‘(’和‘)’的数目。代码如下:

    class Solution(object):
        def generateParenthesis(self, n):
            """
            :type n: int
            :rtype: List[str]
            """
            if not n:
                return []
            cnt = 0 #the number of unadded )
            arr = [')','(']
            res = []
            self.generate([], n, n, res)
            return res
        def generate(self, cur, l, r, res):
            if l > r:  #非常关键
                return 
            if l == 0 and r == 0:
                res.append(''.join(cur))
                return 
            if l > 0:
                cur.append('(')
                self.generate(cur, l-1, r, res)
                cur.pop()
            if r > 0:
                cur.append(')')
                self.generate(cur, l, r-1, res)
                cur.pop()
  • 相关阅读:
    什么是HTTP?
    什么是OSI的第7层
    OSI7层模型
    什么是WAF?
    什么是Mirai僵尸网络
    什么是僵尸网络?
    洛谷 P1208 [USACO1.3]混合牛奶 Mixing Milk
    如何给数组的结构体排序 关于sort用法
    洛谷 P1803 凌乱的yyy / 线段覆盖
    洛谷 P1007 独木桥
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5764756.html
Copyright © 2011-2022 走看看