当前位置:网站首页>每日一题-括号生成-0721
每日一题-括号生成-0721
2022-08-05 05:17:00 【菜鸡程序媛】
题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
- 输入:n = 3
- 输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
思路
- 采用深度优先遍历的方式,先把左括号消耗完,再匹配右括号;右括号走到头的时候,开始回溯
- 当left>right的时候,记得剪枝(因为左括号肯定是先出现的)
代码
public List<String> generateParenthesis(int n) {
List<String> res = new LinkedList<>();
if(n <= 0)
return res;
recur(n, n, new StringBuilder(), res);
return res;
}
private void recur(int left, int right, StringBuilder sb, List<String> res){
if(left == 0 && right == 0){
res.add(sb.toString());
return;
}
// 这个时候要剪枝
if(left > right)
return;
if(left > 0){
sb.append('(');
recur(left - 1, right, sb, res);
sb.deleteCharAt(sb.length() - 1); // 回溯
}
if(right > 0){
sb.append(')');
recur(left, right - 1, sb, res);
sb.deleteCharAt(sb.length() - 1);
}
}
边栏推荐
- idea 快速日志
- [Database and SQL study notes] 10. (T-SQL language) functions, stored procedures, triggers
- LeetCode刷题之第33题
- LeetCode刷题之第416题
- 物联网:LoRa无线通信技术
- [Kaggle project actual combat record] Steps and ideas sharing of a picture classification project - taking leaf classification as an example (using Pytorch)
- C语言入门笔记 —— 分支与循环
- 常用 crud 的思考和设计
- Redis设计与实现(第一部分):数据结构与对象
- 用GAN的方法来进行图片匹配!休斯顿大学提出用于文本图像匹配的对抗表示学习,消除模态差异!
猜你喜欢
随机推荐
leetCode刷题之第31题
framebuffer应用编程及文字显示(2)
【UiPath2022+C#】UiPath Switch
网络信息安全运营方法论 (下)
C语言入门笔记 —— 分支与循环
常见的 PoE 错误和解决方案
电子产品量产工具(4)-UI系统实现
WCH系列芯片CoreMark跑分
It turns out that the MAE proposed by He Yuming is still a kind of data enhancement
Polygon计算每一个角的角度
基于STM32F4的FFT+测频率幅值相位差,波形显示,示波器,时域频域分析相关工程
【UiPath2022+C#】UiPath 数据操作
[Database and SQL study notes] 8. Views in SQL
【ts】typeScript高阶:any和unknown
Machine Learning (1) - Machine Learning Fundamentals
网络信息安全运营方法论 (中)
网络ID,广播地址,掩码位数计算
【ts】typescript高阶:联合类型与交叉类型
一个小时教你如何掌握ts基础
函数在开发环境中的应用(简易实例)









