【LeetCode每天一题】Generate Parentheses(创造有效的括弧)
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(创造有效的括弧)的更多相关文章
- leetcode第21题--Generate Parentheses
problem: Given n pairs of parentheses, write a function to generate all combinations of well-formed ...
- LeetCode 22. 括号生成(Generate Parentheses)
22. 括号生成 22. Generate Parentheses 题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结 ...
- LeetCode 笔记系列五 Generate Parentheses
题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...
- LeetCode(22)Generate Parentheses
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- leetcode第20题--Valid Parentheses
Problem: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if ...
- leetcode个人题解——#22 Generate Parentheses
思路: 递归解决,如果左括号个数小于右括号或者左括号数小于总括号对数,则生成一个左括号,如果左括号数大于右括号,生成一个右括号. class Solution { public: vector< ...
- N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法
回溯法 百度百科:回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步又一次选择,这样的走不通就退回再走的技术为回溯法 ...
- 乘风破浪:LeetCode真题_022_Generate Parentheses
乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...
- [Leetcode][Python]22: Generate Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...
随机推荐
- git diff命令详解
1 如下命令: [devel@localhost pontus]$ git diff webserver/web_pontus/app_api/v0/urls.py# 显示如下: diff --git ...
- rx.js 的冷和热观察
http://cn.rx.js.org/manual/overview.html#h213 https://rxjs-cn.github.io/rxjs5-ultimate-cn/content/ho ...
- Zookeeper中Session Timeout的那些事
前言: RDS系统致力于MySQL数据的高可用,高可靠,高性能以及在线扩展功能,实现这些特性的主要逻辑功能都运行在管理服务器上,一旦管理服务器宕机,数据库的在线扩展功能/备份功能/故障恢复功能等都无从 ...
- 最全面的Android Studio使用教程【申明:来源于网络】
最全面的Android Studio使用教程[申明:来源于网络] http://www.admin10000.com/document/5496.html
- Nodejs----登录验证
1. 写在前面 当我们登录了一个网站,在没有退出登录的情况下,我们关闭了这个网站 ,过一段时间,再次打开这个网站,依然还会是登录状态.这是因为,当我们登录了一个网站,服务器会保存我们的登录状态,直到我 ...
- 今天看到的一些js的用法
以下是今天学习到的一些js语法,特整理出来. 1. (10)["toString"]() === "10" // true 2.如何优雅的取整 var a = ...
- slam course
视频地址:https://www.youtube.com/watch?v=wVsfCnyt5jA 课程网站:http://ais.informatik.uni-freiburg.de/teaching ...
- hive中创建子表并插入数据过程初始化MR报错解决方法
本文继成上一篇通过hive分析nginx日志文章,详情参考下面链接: http://www.cnblogs.com/wcwen1990/p/7066230.html 接着来: 创建业务子表: drop ...
- shell之使用paste命令按列拼接多个文件
试验文件: [root@db03 shell-script]# cat text1.txt 1 2 3 4 5 [root@db03 shell-script]# cat text2.txt orac ...
- iOS知识点持续更新。。。
1.自动布局拉伸和压缩优先级 Autolayout中每个约束都有一个优先级,优先级的范围是1~1000.创建一个约束,默认的优先级最高是1000. Content Hugging Priority:该 ...