当前位置:网站首页>Leetcode brushing questions - 22. Bracket generation
Leetcode brushing questions - 22. Bracket generation
2022-08-05 01:37:00 【lonelyMangoo】
题目地址:22. 括号生成
回溯+判断
Talk about your own ideas first,The first thing you see when you see a question like this is backtracking,My idea is to find all parenthesis combinations first,Then determine whether it meets the requirements of the subject.
Find parenthesis combinations similar to47. 全排列 II
要考虑的东西比较多,Take a good look at it when you go back and refresh the backtracking.
In addition, the stack is used to judge whether it meets the requirements,是20. 有效的括号的简单版
还有就是将listConverted to string is usedjdk8新特性
path.stream().map(String::valueOf).collect(Collectors.joining())
mapis to operate on each element,collectIs the conversion of data collections into objects.
下面是代码:
static boolean[] used;
static Stack<Character> stack;
public static List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
List<Character> path =new ArrayList<>();
used = new boolean[n*2];
char[] nums = new char[n * 2];
//Constructs an array of parentheses
for (int i = 0; i < n; i++) {
nums[i]='(';
nums[i+ n]=')';
}
//回溯
backtrack(path,res,2*n,nums);
return res;
}
private static void backtrack( List<Character> path, List<String> res,int len,char[] nums) {
if(path.size() >= len ){
if(judge(path)){
res.add(path.stream().map(String::valueOf).collect(Collectors.joining()));
}
return;
}
//for 是每一行,
//backbrack是每一层
for (int i = 0; i < len; i++) {
//去重
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
continue;
}
//A small pruning
if(path.size()==0 && nums[i]==')'){
continue;
}
if (!used[i]) {
used[i] = true;
path.add(nums[i]);
backtrack( path, res, len, nums);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
//判断括号
private static boolean judge(List<Character> path) {
stack = new Stack<>();
stack.clear();
for (Character character : path) {
if(character == '(') {
stack.push(character);
}
else if(character == ')'){
if(stack.isEmpty()) {
return false;
}
else {
stack.pop();
}
}
}
return stack.size() == 0;
}
The code is bloated and inefficient,It's a simple idea,It's unlikely to be written in an interview.
After reading the comment area, I got another recursive idea,如下
递归
Think about our needs,其实可以转换成,The opening parenthesis appears before the closing parenthesis,When both the left and right parentheses become n时,The recursion is complete.
List<String> res = new ArrayList<>();
public List<String> generateParenthesis2(int n) {
dfs(n,n,"");
return res;
}
//为什么能用String,因为是不可变类型,不会牵一发而动全身
void dfs(int left,int right,String cur){
if (left==0 && right == 0){
res.add(cur);
}
if(left>0){
dfs(left-1,right,cur+"(");
}
if(left>right){
dfs(left,right-1,cur+")");
}
}
The idea of the code is,When the left parenthesis is still there,Open parentheses are preferred(第二个if),As long as there are currently more left parentheses than right parentheses,You can put the right parenthesis(第三个if).
Just skip the pruning,实在厉害.
边栏推荐
- AI+PROTAC|dx/tx完成500万美元种子轮融资
- 主库预警日志报错ORA-00270
- Dynamic Programming/Knapsack Problem Summary/Summary - 01 Knapsack, Complete Knapsack
- 内存取证系列1
- The difference between a process in user mode and kernel mode [exclusive analysis]
- 蓝牙Mesh系统开发五 ble mesh设备增加与移除
- 数仓4.0(三)------数据仓库系统
- 刷爆朋友圈,Alibaba出品亿级并发设计速成笔记太香了
- Creative code confession
- oracle将restful接口封装到视图中
猜你喜欢
[Endnote] Word inserts a custom form of Endnote document format
5. PCIe official example
深度学习原理学习小结 - Self-Attention/Transformer
【Endnote】Word插入自定义形式的Endnote文献格式
习题:选择结构(一)
第09章 性能分析工具的使用【2.索引及调优篇】【MySQL高级】
张驰咨询:揭晓六西格玛管理(6 Sigma)长盛不衰的秘密
PCIe 核配置
Exploding the circle of friends, Alibaba produced billion-level concurrent design quick notes are too fragrant
Helm Chart
随机推荐
LiveVideoStackCon 2022 Shanghai Station opens tomorrow!
Opencv——视频跳帧处理
MBps与Mbps区别
原生js实现多选框全部选中和取消效果
内存取证系列1
MySQL3
【Redis】Linux下Redis安装
If capturable=False, state_steps should not be CUDA tensors
C# const readonly static 关键字区别
linux(centOs7)部署mysql(8.0.20)数据库
深度学习训练前快速批量修改数据集中的图片名
软件测试技术之最有效的七大性能测试技术
2022杭电多校第一场
仅3w报价B站up主竟带来1200w播放!品牌高性价比B站投放标杆!
GCC:屏蔽动态库之间的依赖
Gartner Hype Cycle:超融合技术将在2年内到达“生产力成熟期”
Is DDOS attack really unsolvable?Do not!
金仓数据库 KingbaseES V8 GIS数据迁移方案(3. 基于ArcGIS平台的数据迁移到KES)
FSAWS 的全球基础设施和网络
动态规划/背包问题总结/小结——01背包、完全背包