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. How to remove ROM in MAME

    /usr/share/games/mame/roms/ /usr/local/share/games/mame/roms/ sudo rm /usr/local/share/games/mame/ro ...

  2. luogu4187

    P4187 [USACO18JAN]Stamp Painting 样例 input3 2 2output6 input6 10 5output190 sol:首先可以发现,对于合法的序列,只要有一串至 ...

  3. servlet篇 之 servlet的访问

    三:servlet的访问 使用web.xml文件中的这个<url-pattern>标签中的映射路径,来访问servlet 6.1 在浏览器的地址栏中,直接输入servlet映射的路径来访问 ...

  4. H5 history.pushState 在微信内修改url后点击用safari打开/复制链接是修改之前的页面

    解决方案:url参数增加随机参数 function wxRefresh() { var replaceQueryParam = (param, newval, search) => { var ...

  5. Codeforces Round #470 Div. 1

    A:暴力枚举x2的因子,由此暴力枚举x1,显然此时减去其最大质因子并+1即为最小x0. #include<iostream> #include<cstdio> #include ...

  6. #195 game(动态规划+二分)

    考虑第一问的部分分.显然设f[i]为i子树从根开始扩展的所需步数,考虑根节点的扩展顺序,显然应该按儿子子树所需步数从大到小进行扩展,将其排序即可. 要做到n=3e5,考虑换根dp.计算某点答案时先将其 ...

  7. Android Spinner 绑定键值对

    这里给大家提供下绑定 spinner键值对的方法. 首先创建绑定模型BaseItem public class BaseItem { public BaseItem(Integer id,String ...

  8. python成长之路一

    1,计算机基础 CPU:中央处理器,相当于人类的大脑,运算中心,控制中心. 内存:暂时储存数据,与CPU交互,8G,16G,32G,64G § 优点:读取速度快. § 缺点:容量小,造价高,断电即消失 ...

  9. spi slaver接口的fpga实现

    前言 spi从机接口程序,数据位8bit,sck空闲时低电平,工作时第一个沿数据传输.只有一个从机,cs低电平片选,slaver开始工作. 流程: 接口定义: 编码实现:(版权所有,请勿用于商业用途, ...

  10. zabbix python 微信告警脚本

    测试zabbix的微信告警耗费了大量时间,使用了开源工具(OneOaaS weixin-alert).shell脚本工具(手动执行正常,服务器调用失败),均没有实现相关功能以下是自己优化过的Pytho ...