• 作者: 负雪明烛
  • 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

判断回溯很简单,拿到一个问题,你感觉如果不穷举一下就没法知道答案,那就可以开始回溯了。

一般回溯的问题有三种:

  1. Find a path to success 有没有解
  2. Find all paths to success 求所有解
    • 求所有解的个数
    • 求所有解的具体信息
  3. Find the best path to success 求最优解

在我的理解中,回溯法是一个剪枝了的二叉树。我们要得到的结果是可以good leaf,如果不满足good leaf就继续向下搜索,搜索的时候需要满足一定的条件。

从上面的图片中我们可以很明显的看到,最后五条画黑线的就是最终的结果,其中左分支都是添加左括号,又分支都是添加右括号。

那么我们在什么情况下添加左括号呢?很明显,最多能添加 n 个左括号,在递归调用的时候,在能传递到最底层的共用字符串中先添加 ”(“ ,然后 left-1,递归调用就可以。

那什么时候添加右括号呢?当左括号个数大于右括号的个数时添加右括号。

总之,向下搜索要满足两个条件:

  1. 插入数量不超过n
  2. 可以插入 的前提是 ( 的数量大于

代码后面的判断条件都是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 括号生成的更多相关文章

  1. [LeetCode]22. Generate Parentheses括号生成

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  2. [LeetCode] 22. Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  3. [leetcode]22. Generate Parentheses生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  4. LeetCode 22 Generate Parentheses(找到所有匹配的括号组合)

    题目链接 : https://leetcode.com/problems/generate-parentheses/?tab=Description   给一个整数n,找到所有合法的 () pairs ...

  5. leetcode@ [22]Generate Parentheses (递归 + 卡特兰数)

    https://leetcode.com/problems/generate-parentheses/ Given n pairs of parentheses, write a function t ...

  6. 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  7. [LeetCode] 22. Generate Parentheses ☆☆

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  8. LeetCode 22. Generate Parentheses

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  9. Java [leetcode 22]Generate Parentheses

    题目描述: Given n pairs of parentheses, write a function to generate all combinations of well-formed par ...

随机推荐

  1. DNS域名解析全过程

    一张图看懂DNS域名解析全过程   DNS域名解析是互联网上非常重要的一项服务,上网冲浪(还有人在用这个词吗?)伴随着大量DNS服务来支撑,而对于网站运营来说,DNS域名解析的稳定可靠,意味着更多用户 ...

  2. Redis—怎么查看Linux有没有安装Redis,如何启动Redis

    1.检测是否有安装redis-cli和redis-server [root@localhost bin]# whereis redis-cli redis-cli: /usr/bin/redis-cl ...

  3. 7本Python必读的入门书籍,你看过吗?(附福利)

    Python入门书籍不用看太多,看一本就够.重要的是你要学习Python的哪个方向,或者说你对什么方向感兴趣,因为Python这门语言的应用领域比较广泛,比如说可以用来做数据分析.机器学习,也可以用来 ...

  4. find命令常见用法

    1. find linux中,find命令一般用来按特定条件查找文件,生产环境中也常用其来过滤文件 名称 find - 搜索目录层次结构中的文件 格式 find [目录] {[选项] [参数]}... ...

  5. 论文翻译:2020_Weighted speech distortion losses for neural-network-based real-time speech enhancement

    论文地址:基于神经网络的实时语音增强的加权语音失真损失 论文代码:https://github.com/GuillaumeVW/NSNet 引用:Xia Y, Braun S, Reddy C K A ...

  6. Flink基础

      一.抽象层次 Flink提供不同级别的抽象来开发流/批处理应用程序. 最低级抽象只提供有状态流.它 通过Process Function嵌入到DataStream API中.它允许用户自由处理来自 ...

  7. Spark(七)【RDD的持久化Cache和CheckPoint】

    RDD的持久化 1. RDD Cache缓存 ​ RDD通过Cache或者Persist方法将前面的计算结果缓存,默认情况下会把数据以缓存在JVM的堆内存中.但是并不是这两个方法被调用时立即缓存,而是 ...

  8. 内存管理——array new,array delete

    1.array new array new就是申请一个数组空间,所以在delete的时候一定不能忘记在delete前加[] delete加上[]符号以后,就相当于告诉系统"我这里是数组对象, ...

  9. Java 设计模式--策略模式,枚举+工厂方法实现

    如果项目中的一个页面跳转功能存在10个以上的if else判断,想要做一下整改 一.什么是策略模式 策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理,最终可以实现解决 ...

  10. 『与善仁』Appium基础 — 22、获取元素信息的操作(一)

    目录 1.获取元素文本内容 (1)text()方法 (2)get_attribute()方法 (3)综合练习 2.获取元素在屏幕上的坐标 1.获取元素文本内容 (1)text()方法 业务场景: 进入 ...