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. 一、kubeadm安装

    一.官网 https://kubernetes.io/zh/docs/setup/independent/install-kubeadm/ 阿里云 kubernetes yum 仓库镜像 安装kube ...

  2. 二、.Net 连接mycat

    一.mycat 单体的mysql已经过去 二.引用Mycat包 三.代码 using Pomelo.Data.MyCat; using System; using System.Collections ...

  3. codeforces749B

    Parallelogram is Back CodeForces - 749B 已知平行四边形的三个顶点,求第四个顶点可能的位置.Input输入有三行,每行包括两个整数x和y ( - 1000 ≤ x ...

  4. linux-shell系列3-wafAPI

    #!/bin/bash datestr=`env LANG=en_US.UTF-8 date -u "+%a, %d %b %Y %H:%M:%S GMT"`pwdstr=`ech ...

  5. 浅析Android设备中grep命令处理流程

    2017-04-18   概述     在TV开发板中,可以在串口中直接使用grep命令.这是因为在/system/bin/下有一个'grep'链接.这个链接指向'/system/bin/toolbo ...

  6. IDEA Failed to prepare an update: Temp directory inside installation

    具体错误: Connection Error Failed to prepare an update: Temp directory inside installation: F:\IDEA_Tool ...

  7. 百度分享不支持https的解决方案(单独部署静态文件)

    首先是参考了博客,下载百度分享的静态代码 static 链接为:https://www.cnblogs.com/mmzuo-798/p/6434576.html 后来在nginx的 nginx.con ...

  8. 【POJ1037】A decorative fence(DP)

    BUPT2017 wintertraining(15) #6C 题意 给长度n的数列,1,2,..,n,按依次递增递减排序,求字典序第k小的排列. 题解 dp. up[i][j]表示长度为j,以第i小 ...

  9. poj1845 sumdiv (因数的和)

    首先分解质因数,$A^B=p_1^{m_1B}p_2^{m_2B}...p_n^{m_nB}$ 然后的话,它的所有因数的和就是$\prod{(1+p_i^1+p_i^2+...+p_i^n)}$ 用一 ...

  10. [WC2008]游览计划(状压dp)

    题面太鬼畜不粘了. 题意就是给一张n*m的网格图,每个点有点权,有k个关键点,让你把这k个关键点连成一个联通快的最小代价. 题解 这题nmk都非常小,解法肯定是状压,比较一般的解法插头dp,但不太好写 ...