【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 ...
随机推荐
- windows下搭建docker
1.下载,双击安装,然后一路next 2.启动,然后打开docker的settings 在shared drives里勾选你想要把项目存放的盘,点击Apply(这里在windows系统下有个坑,项目只 ...
- Angular 定时器$timeout和$interval,延时调用
项目中有用到定时器定时刷新页面的数据,在网上查看了一些资料,整理了一下,备忘. $timeout 用法如下:$timeout(fn,[delay],[invokeApply]); fn:一个将被延迟执 ...
- 【react】---context的基本使用新版---【巷子】
一.全局定义context对象 globalContext.js import React from "react"; const GlobalContext = React.cr ...
- Error creating bean with name 'eurekaAutoServiceRegistration'
spring-boot项目不断重启,报错: org.springframework.beans.factory.BeanCreationNotAllowedException: Error creat ...
- SQL命令中的case...when...then...else...end条件查询
select b.XH, b.ZBXH, a.SJKSMC, a.JCRQ, a.JYRQ, a.JCJBMC, a.CYZMC, b.CY ...
- gensim Word2Vec 训练和使用(Model一定要加载到内存中,节省时间!!!)
训练模型利用gensim.models.Word2Vec(sentences)建立词向量模型该构造函数执行了三个步骤:建立一个空的模型对象,遍历一次语料库建立词典,第二次遍历语料库建立神经网络模型可以 ...
- 编译安装spark 1.5.x(Building Spark)
原文连接:http://spark.apache.org/docs/1.5.0/building-spark.html · Building with build/mvn · Building a R ...
- airflow docker
https://github.com/puckel/docker-airflow 镜像介绍:https://hub.docker.com/r/puckel/docker-airflow/ docker ...
- 【Linux】Linux 常用命令汇总
查看软件xxx安装内容:dpkg -L xxx 查找软件库中的软件:apt-cache search 正则表达式 查找软件库中的软件:aptitude search 软件包 查找文件属于哪个包:dpk ...
- Anaconda 虚拟环境安装及应用
首先要安装Anaconda 下载网址:https://www.anaconda.com/distribution/#download-section Miniconda下载网址:https: ...