【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 ...
随机推荐
- vue setTimeout 注销
vue在切换页面时,销毁了上衣个组件,上一个页面的也要相应的setTimeout 注销: setTimeout(function () { if(that && !that._isDe ...
- F#周报2018年第52期
新闻 Sudokube--使用Fable开发的数独立方体 Rust 2019年及以后的发展 视频及幻灯片 我爱F#代码 马蒂亚斯·布兰在Developer On Fire上的演讲--有条理的和有趣的 ...
- MySQL之视图、触发器、事务、存储过程、函数 流程控制
MySQL之视图.触发器.事务.存储过程.函数 阅读目录 一 视图 二 触发器 三 事务 四 存储过程 五 函数 六 流程控制 MySQL这个软件想将数据处理的所有事情,能够在mysql这个层面上全部 ...
- [No0000156]天干地支-狗年我懂,戊戌二字怎么来的?
话说,这几年的年份,总能让人联想到历史课本.比如,2014年是甲午马年,是中日甲午战争120周年.而2018年是戊戌狗年,嗯,戊戌变法也过去120年了…… 狗年相信大家都了解,小观前面两期关于反犬旁和 ...
- [No000011C]使人醒悟的生活中的定律
1. 墨菲定律 我们在事前应该是尽可能想得周到.全面一些,如果真的发生不幸或者损失,就笑着应对吧,关键在于总结所犯的错误,而不是企图掩盖它. 2. 羊群效应 对他人的信息不可全信也不可 ...
- centos7安装zabbix3.4
一.系统环境 关闭防火墙及selinux systemctl stop firewalld.service systemctl disable firewalld.service sed -i 's/ ...
- 深入hash
hash真的很好用,这些杂一点的知识点我觉得还是很有必要的,对还有离散化. 1<=N<=1,000,000,其它所有数据都在[0...1,000,000,000]范围内 看起来很简单一道水 ...
- dbgrideh添加列、多表头及属性
(一)动态添加列 procedure TForm2.FormCreate(Sender: TObject); var vCol : TColumn; begin vCol := DBGrid1 ...
- tomcat端口设置
在tomcat安装目录下,编辑/conf/server.properties 更改对应的端口: 然后系统重启就可以了.
- xpath定位方法详解
1.xpath较复杂的定位方法: 现在要引用id为“J_password”的input元素,可以像下面这样写: WebElement password = driver.findElement(By. ...