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. python 读取csv 数据并画图分析

    数据源 : https://pan.baidu.com/s/1eR593Uy    密码: yqjh python环境 python3 #encoding: utf-8 import csv impo ...

  2. Nintex Workflow Get Attachment link

    不多解释,直接上图,操作简单

  3. B-树 B+树复习总结

    一.B-树的定义 一棵m阶的B-树或为空树,或为具有以下特性的m叉树 1.树中每个结点至多有m棵子树 (m-1个关键字) 2.根结点至少有两棵子树 (至少有一个关键字) 3.除根节点的分支结点至少有f ...

  4. C 语言----- 指针

    指针是一个值为内存地址的变量, 指针的核心是它是一个变量, 只不过它是用来存放内存地址的, 所以在了解指针之前,先说一下什么是变量.变量就是在内存中开辟的一个空间.如int year, 就是在内存中开 ...

  5. qss 的使用

    //设置样式表 QStringList qss; qss.append("QFrame{border:0px solid #00BB9E;}"); // qss.append(&q ...

  6. Luogu4389 付公主的背包(生成函数+多项式exp)

    显然构造出生成函数,对体积v的物品,生成函数为1+xv+x2v+……=1/(1-xv).将所有生成函数乘起来得到的多项式即为答案,设为F(x),即F(x)=1/∏(1-xvi).但这个多项式的项数是Σ ...

  7. ZOJ 1403 解密

    参考自:https://www.cnblogs.com/ECJTUACM-873284962/p/6412212.htmlSafecracker Time Limit: 2 Seconds       ...

  8. 爬虫_电影天堂 热映电影(xpath)

    写了一天才写了不到100行.不过总归是按自己的思路完成了 import requests from lxml import etree import time BASE = 'http://www.d ...

  9. iptable四表五链

    链(内置): PREROUTING:对数据包作路由选择前应用此链中的规则: INPUT:进来的数据包应用此规则链中的策略: FORWARD:转发数据包时应用此规则链中的策略: OUTPUT:外出的数据 ...

  10. POJ 2672 Tarjan + 缩点 + 拓扑思想

    Going from u to v or from v to u? Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 17383 ...