当前位置:网站首页>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
边栏推荐
- 構建元宇宙時代敏捷制造的九種能力
- [hdu6833] a very easy math problem
- Realize data value through streaming data integration (2)
- NEC infrared remote control coding description
- NEC红外遥控编码说明
- A concise course of fast Fourier transform FFT
- LeetCode-608. 树节点
- 101. Symmetric Tree
- C language: expression evaluation (integer promotion, arithmetic conversion...)
- Examination questions and answers of the third batch (main person in charge) of Guangdong safety officer a certificate in 2022
猜你喜欢

0704、ansible----01

《谷雨系列》空投

Interviewer: let's talk about some commonly used PHP functions. Fortunately, I saw this article before the interview

0704、ansible----01

Nine abilities of agile manufacturing in the era of meta universe

The central control learning infrared remote control module supports network and serial port control

Depth selector

防疫登记小程序

shell脚本免交互

2022年广东省安全员A证第三批(主要负责人)考试试题及答案
随机推荐
[CF 1425d] danger of mad snakes
Configuration of LNMP
Nvidia最新三维重建技术Instant-ngp初探
Sim Api User Guide(4)
Windows安装redis并将redis设置成服务开机自启
ansible 云计算 自动化 命令行精简版
LeetCode 1249. Minimum Remove to Make Valid Parentheses - FB高频题1
Epidemic prevention registration applet
構建元宇宙時代敏捷制造的九種能力
1D / 1D dynamic programming learning summary
"Gu Yu series" airdrop
Classic routine: DP problem of a kind of string counting
Depth selector
工业元宇宙平台规划与建设
2022年制冷与空调设备运行操作考试练习题及模拟考试
Prefix sum of integral function -- Du Jiao sieve
DBA common SQL statements (3) - cache, undo, index and wait events
Yarn资源调度器
P1446 [hnoi2008] cards (Burnside theorem + DP count)
Chapter II in memory architecture (im-2.2)