【LeetCode】22. Generate Parentheses 括号生成
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
- 个人公众号:负雪明烛
- 本文关键词:括号, 括号生成,题解,leetcode, 力扣,Python, C++, Java
题目地址:https://leetcode.com/problems/generate-parentheses/description/
题目描述
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,要输出n个左括号和右括号能匹配的所有字符串。
解题方法
回溯法
仍然是回溯法的题目,回溯法的题目可以看看这个文章:
https://segmentfault.com/a/1190000006121957
判断回溯很简单,拿到一个问题,你感觉如果不穷举一下就没法知道答案,那就可以开始回溯了。
一般回溯的问题有三种:
- Find a path to success 有没有解
- Find all paths to success 求所有解
- 求所有解的个数
- 求所有解的具体信息
- Find the best path to success 求最优解
在我的理解中,回溯法是一个剪枝了的二叉树。我们要得到的结果是可以good leaf,如果不满足good leaf就继续向下搜索,搜索的时候需要满足一定的条件。
从上面的图片中我们可以很明显的看到,最后五条画黑线的就是最终的结果,其中左分支都是添加左括号,又分支都是添加右括号。
那么我们在什么情况下添加左括号呢?很明显,最多能添加 n 个左括号,在递归调用的时候,在能传递到最底层的共用字符串中先添加 ”(“ ,然后 left-1,递归调用就可以。
那什么时候添加右括号呢?当左括号个数大于右括号的个数时添加右括号。
总之,向下搜索要满足两个条件:
- 插入数量不超过n
- 可以插入
)
的前提是(
的数量大于)
代码后面的判断条件都是if,而不是elif,因为是满足两个条件的任意一个就可以继续向下搜索,而不是同时只能满足其中的一个。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
self.dfs(res, n, n, '')
return res
def dfs(self, res, left, right, path):
if left == 0 and right == 0:
res.append(path)
return
if left > 0:
self.dfs(res, left - 1, right, path + '(')
if left < right:
self.dfs(res, left, right - 1, path + ')')
二刷,使用C++,基本结构和上面一样,不过这里lc和rc分别表示左括号的个数和右括号的个数。vector的push_back()方法调用的时候实际上是使用的值传递,也就是会进行赋值到vector里。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
int lc = 0, rc = 0;
dfs(res, "", n, lc, rc);
return res;
}
void dfs(vector<string>& res, string path, int n, int lc, int rc) {
if (rc > lc || lc > n || rc > n) return;
if (lc == rc && lc == n) {
res.push_back(path);
return;
}
dfs(res, path + '(', n, lc + 1, rc);
dfs(res, path + ')', n, lc, rc + 1);
}
};
日期
2018 年 2 月 24 日
2018 年 12 月 14 日 —— 12月过半,2019就要开始
2020 年 4 月 9 日 —— 天气好暖和呀
【LeetCode】22. Generate Parentheses 括号生成的更多相关文章
- [LeetCode]22. Generate Parentheses括号生成
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [LeetCode] 22. Generate Parentheses 生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [leetcode]22. Generate Parentheses生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- LeetCode 22 Generate Parentheses(找到所有匹配的括号组合)
题目链接 : https://leetcode.com/problems/generate-parentheses/?tab=Description 给一个整数n,找到所有合法的 () pairs ...
- leetcode@ [22]Generate Parentheses (递归 + 卡特兰数)
https://leetcode.com/problems/generate-parentheses/ Given n pairs of parentheses, write a function t ...
- 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- [LeetCode] 22. Generate Parentheses ☆☆
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- LeetCode 22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- Java [leetcode 22]Generate Parentheses
题目描述: Given n pairs of parentheses, write a function to generate all combinations of well-formed par ...
随机推荐
- 毕业设计之LNP+DISCUZ +分离的数据库操作
环境介绍: CentOS6.9最小化安装 https://nginx.org/download/nginx-1.16.1.tar.gz https://www.php.net/distribution ...
- perl 数组快速去除重复元素
这里记录两种perl数组去重的办法,一种利用哈希(hash),一种直接利用perl自带的模块List::MoreUtils内部的函数uniq. 一.利用hash去重 示例代码如下: 1 #!/usr/ ...
- 在windows 10家庭版上安装docker的步骤
本人之前写Redis书和Spring Cloud Alibaba书时,发现一些分布式组件更适合安装在linux环境,而在搭建Redis等集群时,更需要linux环境. 本人日常练习代码和写书所用的机器 ...
- 基于MQTT协议实现远程控制的"智能"车
智能,但不完全智能 虽然我不觉得这玩意儿有啥智能的,但都这么叫就跟着叫喽. 时隔好几天才写的 其实在写这篇博文的时候我已经在做升级了,并且已经到了中后期阶段了. 主要是业余时间做着玩,看时间了. 规格 ...
- Spark(四)【RDD编程算子】
目录 测试准备 一.Value类型转换算子 map(func) mapPartitions(func) mapPartitions和map的区别 mapPartitionsWithIndex(func ...
- set、multiset深度探索
set/multiset的底层是rb_tree,因此它有自动排序特性.set中的元素不允许重复必须独一无二,key与value值相同,multiset中的元素允许重复. set的模板参数key即为关键 ...
- Template Metaprogramming in C++
说实话,学习C++以来,第一次听说"Metaprogramming"这个名词. Predict the output of following C++ program. 1 #in ...
- Linux学习 - shell脚本执行
一.shell概述 shell是一个命令行解释器,为用户提供一个向Linux内核发送请求以便运行程序的界面系统级程序,用户可以用shell来启动.挂起.停止甚至是编写一些程序 shell还是一个功能强 ...
- spring mvc idea创建
创建项目 创建项目 --> Spring --> Spring MVC --> 下面选择Download,会显示Spring MVC-5版本 如果是首次使用IDEA,因为没有配置ma ...
- 【科研工具】CAJViewer的一些操作
逐渐发现CAJViewer没有想象中的难用. 添加书签:Ctrl+M 使用按类分类,可以筛选出书签位置,和注释区分. 搜索:Ctrl+F 可以定义多种搜索.