22. Generate Parentheses

 . Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = , a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        if n == 0: return ['']
        ans = []
        for c in xrange(n):
            for left in self.generateParenthesis(c):
                for right in self.generateParenthesis(n-1-c):
                    ans.append('({}){}'.format(left, right))
        return ans
class Solution(object):
    # Brute Force
    def generateParenthesis(self, n):
        def generate(A=[]):
            if len(A) == 2 * n:
                if valid(A):
                    ans.append("".join(A))
            else:
                A.append('(')
                generate(A)
                A.pop()
                A.append(')')
                generate(A)
                A.pop()

        def valid(A):
            bal = 0
            for c in A:
                if c == '(':
                    bal += 1
                else:
                    bal -= 1
                if bal < 0: return False
            return bal == 0

        ans = []
        generate()
        return ans

# Backtracking
    def generateParenthesis2(self, N):
        ans = []

        def backtrack(S='', left=0, right=0):
            if len(S) == 2 * N:
                ans.append(S)
                return
            if left < N:
                backtrack(S + '(', left + 1, right)
            if right < left:
                backtrack(S + ')', left, right + 1)

        backtrack()
        return ans

# Closure Number
    def generateParenthesis3(self, N):
        if N == 0: return ['']
        ans = []
        for c in range(N):
        # for c in xrange(N):
            for left in self.generateParenthesis(c):
                for right in self.generateParenthesis(N - 1 - c):
                    ans.append('({}){}'.format(left, right))
        return ans

sn = Solution()
print(sn.generateParenthesis(3))

print(sn.generateParenthesis2(3))

print(sn.generateParenthesis3(3))

xrange and format

22. Generate Parentheses(ML)的更多相关文章

  1. [Leetcode][Python]22: Generate Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...

  2. 刷题22. Generate Parentheses

    一.题目说明 这个题目是22. Generate Parentheses,简单来说,输入一个数字n,输出n对匹配的小括号. 简单考虑了一下,n=0,输出"";n=1,输出" ...

  3. 【LeetCode】22. Generate Parentheses (2 solutions)

    Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...

  4. 22. Generate Parentheses (recursion algorithm)

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  5. [LeetCode] 22. Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  6. LeetCode 22. Generate Parentheses

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  7. 22. Generate Parentheses——本质:树,DFS求解可能的path

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  8. Java [leetcode 22]Generate Parentheses

    题目描述: Given n pairs of parentheses, write a function to generate all combinations of well-formed par ...

  9. leetcode@ [22]Generate Parentheses (递归 + 卡特兰数)

    https://leetcode.com/problems/generate-parentheses/ Given n pairs of parentheses, write a function t ...

随机推荐

  1. vue自定義指令

    自定義指令可以允許代碼複用, 全局自定義指令 vue.directive('指令名',{鉤子函數:指令函數}) 局部自定義指令: vue({ directives:{指令名:{鉤子函數:指令函數} } ...

  2. 打包一个UWP APP

    Before packaging your app Test your app. Before you package your app for store submission, make sure ...

  3. [BZOJ 3498] [PA 2009] Cakes

    Description \(n\) 个点 \(m\) 条边,每个点有一个点权 \(a_i\). 对于任意一个三元环 \((i,j,k)(i<j<k)\),它的贡献为 \(\max(a_i, ...

  4. BZOJ4514[Sdoi2016]数字配对——最大费用最大流

    题目描述 有 n 种数字,第 i 种数字是 ai.有 bi 个,权值是 ci. 若两个数字 ai.aj 满足,ai 是 aj 的倍数,且 ai/aj 是一个质数, 那么这两个数字可以配对,并获得 ci ...

  5. [Codeforces261D]Maxim and Increasing Subsequence——树状数组+DP

    题目链接: Codeforces261D 题目大意:$k$次询问,每次给出一个长度为$n$的序列$b$及$b$中的最大值$maxb$,构造出序列$a$为$t$个序列$b$连接而成,求$a$的最长上升子 ...

  6. 复习 LIS nlogn

    参考:https://www.cnblogs.com/wxjor/p/5524447.html 最长下降只要把符号都倒过来就行 在栈中二分找第一个比当前值小的替换就行

  7. ☆ [HDU2089] 不要62「数位DP」

    类型:数位DP 传送门:>Here< 题意:问区间$[n,m]$的数字中,不含4以及62的数字总数 解题思路 数位DP入门题 先考虑一般的暴力做法,整个区间扫一遍,判断每个数是否合法并累计 ...

  8. python中可变参数和关键字参数总结

    #_*_coding='utf-8' #可变参数 def person(name,age,*args): #定义了可变参数args print('传入的名字为:',name) print('传入的年龄 ...

  9. 【XSY2754】求和 莫比乌斯反演 杜教筛

    题目描述 给你\(n,p\),求 \[ \sum_{i=1}^n\sum_{j=1}^i\sum_{k=1}^i\gcd(i,j,k)\mod p \] \(n\leq {10}^9\) 题解 \[ ...

  10. wstngfw openVpn站点到站点连接示例(共享密钥)

    wstngfw openVpn站点到站点连接示例(共享密钥) 在本例中,将假设以下设置: 站点 A 站点 B 名称 Beijing Office(北京办公室) 名称 Shenzheng Office( ...