Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.    For example, given n = 3, a solution set is

[

  "((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路

  比较简单的方法是暴力破解法我们生成所有可能的组合,然后逐一去判断他们是否满足要求,最后输出一个满足的集合。但是这种方法当n非常大时,会存在时间复杂度非常高的问题。这会导致运行时间超时。
  时间复杂度为(22nn), 对于n个字符串可以产生22n个结果,然后每一个结果需要判断其是否有效,遍历需要O(n)。空间复杂度为(22nn)。
  另外一种方法是,我们可以根据有效括弧的规则来进行判断,当'('不为0时,可以一直添加,而')'的添加,我们需要满足他的添加个数不能大于'('的数量,否则直接为无效的括弧。 暴力破解思路


 class Solution(object):
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
第二种解决代码

 class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n <2: # 小于2时,直接根据值进行返回。
return '' if n == 0 else ['()']
res = [] # 存储结果集
s=''
self.get_res(s, res, 0, 0 , n) # 调用制造函数
return res def get_res(self, s, res, left,right, n):
if len(s) == n*2: # 直接将结果添加进结果集中
res.append(s)
return
if left < n: # 左括号小于n时,直接进行添加。并且left+1
self.get_res(s+'(', res, left+1, right, n)
if right < left:
self.get_res(s+')', res, left, right+1, n)

【LeetCode每天一题】Generate Parentheses(创造有效的括弧)的更多相关文章

  1. leetcode第21题--Generate Parentheses

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

  2. LeetCode 22. 括号生成(Generate Parentheses)

    22. 括号生成 22. Generate Parentheses 题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结 ...

  3. LeetCode 笔记系列五 Generate Parentheses

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

  4. LeetCode(22)Generate Parentheses

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

  5. leetcode第20题--Valid Parentheses

    Problem: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if ...

  6. leetcode个人题解——#22 Generate Parentheses

    思路: 递归解决,如果左括号个数小于右括号或者左括号数小于总括号对数,则生成一个左括号,如果左括号数大于右括号,生成一个右括号. class Solution { public: vector< ...

  7. N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法

    回溯法 百度百科:回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步又一次选择,这样的走不通就退回再走的技术为回溯法 ...

  8. 乘风破浪:LeetCode真题_022_Generate Parentheses

    乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...

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

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

随机推荐

  1. 使用 vm 加载文件中的数据到变量里面

    .json 不能写注释, 还需要严格的双引号 或者使用 .json5 // test.db [ // name {name: 1} ] // test.js const fs = require('f ...

  2. html5__Notifications API 桌面通知

    MDN地址 google 文档 https://developers.google.cn/web/fundamentals/push-notifications/ const koa2 = requi ...

  3. win10 开启蓝 由于其配置信息(注册表中的)不完整或已损坏

    在管理员命令提示符下键入以下命令: Dism /Online /Cleanup-Image /ScanHealth 这条命令将扫描全部系统文件并和官方系统文件对比,扫描计算机中的不一致情况. Dism ...

  4. vs2017默认以管理员运行

    1. 打开VS的安装目录,找到devenv.exe,右键,选择“兼容性疑难解答”. 2. 选择“疑难解答程序” 3. 选择“该程序需要附加权限” 4. 确认用户帐户控制后,点击测试程序,不然这个对话框 ...

  5. ERP项目实施记录01

    工厂8月中与某ERP服务商签约,至今已经过去4个月,顾问服务了13人天,进行了10次培训. 内部产生项目文档1个:物料编码方案 制度:0个 流程:无 因ERP服务商不是针对本行业的,在BOM和生产计划 ...

  6. PL-SLAM

    双目 1.PL-SLAM: a Stereo SLAM System through the Combination of Points and Line Segments ubuntu14.04配置 ...

  7. WPF 依赖属性和附加属性

    依赖属性: 依赖属性就是自己没有值,通过Binding从数据源获得值,就是依赖在别人身上,拥有依赖属性的对象称为依赖对象. 依赖属性的值存在哪里? 在WPF运行时,维护了一个全局的Hashtable存 ...

  8. window.onresize监听事件

    window.onresize监听事件 onresize 事件会在窗口或框架被调整大小时发生. 支持onresize的标签:<a>, <address>, <b>, ...

  9. set,env,export,set -x,set -e;

    set 用来显示本地变量 env 用来显示环境变量 export 用来显示和设置环境变量 set 显示当前shell的变量,包括当前用户的变量 env 显示当前用户的变量 export 显示当前导出成 ...

  10. PHP进阶-PHP执行和加速原理