当前位置:网站首页>每日一题-括号生成-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);
}
}
边栏推荐
- 【UiPath2022+C#】UiPath 练习和解决方案-变量、数据类型和控制流程
- C语言入门笔记 —— 函数(1)
- [Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)
- 网络信息安全运营方法论 (下)
- 物联网-广域网技术之NB-IoT
- dataframe 常用操作
- GIS面试问题
- LeetCode刷题之第61题
- 七、请求处理——Map、Model类型参数处理原理
- ECCV2022 | RU & Google propose zero-shot object detection with CLIP!
猜你喜欢
![[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)](/img/ac/884d8aba8b9d363e3b9ae6de33d5a4.png)
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)

Tensorflow steps on the pit notes and records various errors and solutions

原来何恺明提出的MAE还是一种数据增强

沁恒MCU从EVT中提取文件建立MounRiver独立工程

It turns out that the MAE proposed by He Yuming is still a kind of data enhancement

LeetCode刷题之第23题

leetCode刷题之第31题

电子产品量产工具(2)- 输入系统实现

发顶会顶刊论文,你应该这样写作

网工必用神器:网络排查工具MTR
随机推荐
手把手教你搭建小程序
CAN、CAN FD
关于使用QML的MediaPlayer实现视频和音频的播放时遇到的一些坑
ECCV2022 | RU&谷歌提出用CLIP进行zero-shot目标检测!
五、请求处理—Rest映射是怎样实现的?
六、请求处理—获取请求参数系列注解是怎样工作的?
单变量线性回归
【22李宏毅机器学习】课程大纲概述
The University of Göttingen proposed CLIPSeg, a model that can perform three segmentation tasks at the same time
GIS面试问题
【ts】typescript高阶:分布式条件类型
leetCode刷题之第31题
[After a 12] No record for a whole week
AIDL detailed explanation
C语言—扫雷的实现
「实用」运维新手一定不能错过的17 个技巧
《基于机器视觉的输电线路交叉点在线测量方法及技术方案》论文笔记
HuiFer 带你读懂 BeanFactory getBean 方法
[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)
LeetCode刷题之第416题