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. 【NLP】自然语言处理:词向量和语言模型

    声明: 这是转载自LICSTAR博士的牛文,原文载于此:http://licstar.net/archives/328 这篇博客是我看了半年的论文后,自己对 Deep Learning 在 NLP 领 ...

  2. Auth模块使用方法大全

    auth认证 导包 from django.contrib import auth 默认数据库中使用auth_user表 创建超级用户 python manage.py createsuperuser ...

  3. python----re正则模块详解

    今天介绍一下Python中常用的正则表达式处理函数.Python的正则表达式主要有两种方法完成模式匹配:『搜索』和『匹配』 re.match re.match 尝试从字符串的开始全部或者部分匹配某个模 ...

  4. qt 在窗口上画框

    在窗口w上面画个黄色的框:在窗口上添加一个label,然后在label上画框 QLabel label(&w); label.setScaledContents(true); QPixmap ...

  5. Codeforces Round #443 Div. 1

    A:考虑每一位的改变情况,分为强制变为1.强制变为0.不变.反转四种,得到这个之后and一发or一发xor一发就行了. #include<iostream> #include<cst ...

  6. 学习Android过程中遇到的问题及解决方法——网络请求

    在学习Android的网络连接时遇到崩溃或异常(出现的问题就这两个,但是不稳定)的问题,先上代码,看看哪里错了(答案在文末) activity_main.xml: <?xml version=& ...

  7. 【XSY2691】中关村 卢卡斯定理 数位DP

    题目描述 在一个\(k\)维空间中,每个整点被黑白染色.对于一个坐标为\((x_1,x_2,\ldots,x_k)\)的点,他的颜色我们通过如下方式计算: 如果存在一维坐标是\(0\),则颜色是黑色. ...

  8. npm config 删除变量

    问题 安装npm时,使用npm config set 命令重新设置了变量,但是设置变量时少了个空格,设置错了.使用npm config ls -l 查看环境变量 添加错的这一个,应该如何删除? 解决 ...

  9. JeeSite 部署到linux服务器

    1.打包 改数据库连接 打包war包https://www.cnblogs.com/wdw31210/p/9878422.html 2.上传到linux 服务器的tomcat/webapps/ 下 安 ...

  10. 诶西,JavaScript学习记录。。。。。。

    由于大学课程缘故,老师巨爱叫人问问题,还记分呢,随便记录一下Js的学习情况,以后复习什么的也比较方便吧...... 开始咯,就按照C语言学习那样的方法来吧! ===================== ...