【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 ...
随机推荐
- QQ音乐flac音乐转MP6格式怎样实现
很多时候我们所下载的音乐格式都不是MP3格式的,用起来都是有局限性的,因为很多播放器都是支持MP3格式的.很多时候为了方便使用,我们就需要将不同的音乐格式转换为MP3格式的.如flac音乐转MP3的问 ...
- oracle的存储过程
plsql中执行无参数存储过程格式: begin tttttttttttttt;end; 在执行记录表中 select *from v$sqlarea t where t.sql_text like ...
- jdbc--------JdbcUtilDao 类
2018-12-14 目标:做成一个比较通用的 sql 操作 import com.ljs.util.JDBCUtil; 类名:JdbcUtilDao 1: 更新操作, 针对任何表,增加,删除,更新操 ...
- HDU 4699 - Editor - [对顶栈]
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4699 Problem Description Sample Input8I 2I -1I 1Q 3LD ...
- flannel
Docker跨主机容器间网络通信实现的工具有Pipework.Flannel.Weave.Open vSwitch(虚拟交换机).Calico实现跨主机容器间的通信.其中Pipework.Weave. ...
- nginx内置变量 大全
nginx内置变量 内置变量存放在 ngx_http_core_module 模块中,变量的命名方式和apache 服务器变量是一致的.总而言之,这些变量代表着客户端请求头的内容,例如$http_u ...
- sed中支持变量的处理方法
1.eval sed ’s/$a/$b/’ filename2.sed "s/$a/$b/" filename3.sed ’s/’$a’/’$b’/’ filename 4.sed ...
- LeetCode 589 N-ary Tree Preorder Traversal 解题报告
题目要求 Given an n-ary tree, return the preorder traversal of its nodes' values. 题目分析及思路 题目给出一棵N叉树,要求返回 ...
- linux下tomcat启动没有日志,没有进程,没有报错,没有监听端口
可以试试运行catalina.sh run,这个命令会让tomcat在终端打印日志.
- spring+shiro+springmvc+maven权限卡控示例
项目结构 UserController , 主要负责用户登入和注销. LinewellController, 主要负责请求受权限卡控的数据. MyRealm,自定义realm. Authorizati ...