当前位置:网站首页>每日一题-括号生成-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);
}
}
边栏推荐
- 十一、拦截器运行原理
- 六、请求处理—获取请求参数系列注解是怎样工作的?
- 将一句话的单词进行倒置(C语言纯代码)
- MaskDistill - Semantic segmentation without labeled data
- [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)
- 吞吐?带宽?傻傻分不清楚
- 十、视图解析原理与源码分析
- ACL 的一点心得
- 【ts】typescript高阶:分布式条件类型
- 亲身实感十多年的面试官面试的题目
猜你喜欢

IT系统运行维护方法及策略

LeetCode刷题之第33题

用GAN的方法来进行图片匹配!休斯顿大学提出用于文本图像匹配的对抗表示学习,消除模态差异!
![[Pytorch study notes] 11. Take a subset of the Dataset and shuffle the order of the Dataset (using Subset, random_split)](/img/59/ce3e18f32c40a97631f5ac1b53662a.png)
[Pytorch study notes] 11. Take a subset of the Dataset and shuffle the order of the Dataset (using Subset, random_split)

PoE视频监控解决方案

CVPR2020 - 自校准卷积

网工必用神器:网络排查工具MTR
![[Kaggle project actual combat record] Steps and ideas sharing of a picture classification project - taking leaf classification as an example (using Pytorch)](/img/7d/7f1301c30034f1c247d41f04c40244.png)
[Kaggle project actual combat record] Steps and ideas sharing of a picture classification project - taking leaf classification as an example (using Pytorch)

读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping

五、请求处理—Rest映射是怎样实现的?
随机推荐
Facial Motion Capture 调研
【Multisim仿真】直流稳压电源设计报告
六步搞定子网划分
Tensorflow steps on the pit notes and records various errors and solutions
《基于机器视觉测量系统的工业在线检测研究》论文笔记
Redis集群(docker版)——从原理到实战超详细
[Database and SQL study notes] 9. (T-SQL language) Define variables, advanced queries, process control (conditions, loops, etc.)
Jupyter notebook选择不同的Anaconda环境作为内核运行
CVPR2020 - 自校准卷积
数控直流电源
深度学习系列(二)优化器 (Optimization)
PID详解
沁恒MCU从EVT中提取文件建立MounRiver独立工程
五、请求处理—Rest映射是怎样实现的?
CVPR 2022 |节省70%的显存,训练速度提高2倍
CVPR best paper winner Huang Gao's team from Tsinghua University presented the first dynamic network review
You should write like this
【nodejs】第一章:nodejs架构
Polygon计算每一个角的角度
【UiPath2022+C#】UiPath变量和参数