当前位置:网站首页>Leetcode22:括号生成
Leetcode22:括号生成
2022-04-23 10:07:00 【VipPeterGee】
题目
- 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合
解法
private static List<String> generate(int n) {
List<String> dataList=new ArrayList<>();
if (n==0)return dataList;
dfs("",n,n,dataList);
return dataList;
}
- DFS做减法方式
private static void dfs(String current, int left, int right, List<String> dataList) {
// 递归结束添加到list中
if (left==0&&right==0){
dataList.add(current);
return;
}
if (left>right){
return;
}
if (left>0){
dfs(current+"(",left-1,right,dataList);
}
if (right>0){
dfs(current+")",left,right-1,dataList);
}
}
- DFS做加法方式
private static void dfsIncrease(String current, int left, int right,int length, List<String> dataList) {
// 递归结束添加到list中
if (left==length&&right==length){
dataList.add(current);
return;
}
if (left<right){
return;
}
if (left<length){
dfsIncrease(current+"(",left+1,right,length,dataList);
}
if (right<length){
dfsIncrease(current+")",left,right+1,length,dataList);
}
}
- 参考: https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/
版权声明
本文为[VipPeterGee]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sinat_35241409/article/details/124338347
边栏推荐
- Sim Api User Guide(7)
- Realize data value through streaming data integration (3) - real-time continuous data collection
- 第一章 Oracle Database In-Memory 相关概念(续)(IM-1.2)
- DBA常用SQL语句(3)- cache、undo、索引和等待事件
- Educational Codeforces Round 81 (Rated for Div. 2)
- [CF 1425d] danger of mad snakes
- 计算机网络安全实验二|DNS协议漏洞利用实验
- ansible 云计算 自动化
- 元宇宙时代的职业规划与执行
- Epidemic prevention registration applet
猜你喜欢
Failureforwardurl and failureurl
Planning and construction of industrial meta universe platform
Career planning and implementation in the era of meta universe
Nvidia最新三维重建技术Instant-ngp初探
"Gu Yu series" airdrop
[untitled]
[COCI] lattice (dichotomy + tree divide and conquer + string hash)
MapReduce核心和基础Demo
[untitled]
JUC concurrent programming 09 -- source code analysis of condition implementation
随机推荐
Juc并发编程09——Condition实现源码分析
F-niu Mei's apple tree (diameter combined)
1D / 1D dynamic programming learning summary
杰理之系统事件有哪些【篇】
Realize data value through streaming data integration (1)
构建元宇宙时代敏捷制造的九种能力
DBA常用SQL语句(2)— SGA和PGA
Shell script interaction free
Function realization of printing page
[hdu6868] absolute math (pusher + Mobius inversion)
【无标题】
JUC concurrent programming 07 -- is fair lock really fair (source code analysis)
Realizing data value through streaming data integration (5) - stream processing
Go language practice mode - functional options pattern
CSP certification 202203-2 travel plan (multiple solutions)
Question bank and answers of Shanghai safety officer C certificate examination in 2022
Understand scope
SQL tuning series - Introduction to SQL tuning
通过流式数据集成实现数据价值(5)- 流分析
Using idea to develop Spark Program