当前位置:网站首页>【力扣】22.括号生成
【力扣】22.括号生成
2022-08-11 03:44:00 【aigo-2021】
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的括号组合。
示例 1:
输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:
输入:n = 1
输出:[“()”]
提示:
1 <= n <= 8
深度优先遍历:树形结构图
分析:
- 当前左右括号都有大于 0 个可以使用的时候,才产生分支;
- 产生左分支的时候,只看当前是否还有左括号可以使用;
- 产生右分支的时候,还受到左分支的限制,右边剩余可以使用的括号数量一定得在严格大于左边剩余的数量的时候,才可以产生分支;
- 在左边和右边剩余的括号数都等于 0 的时候结算。
代码:
class Solution {
// 做减法
public List<String> generateParenthesis(int n) {
List<String> list= new ArrayList<>();
// 执行深度优先遍历,搜索可能的结果
dfs("", n, n, list);
return list;
}
/** * @param str 当前递归得到的结果 * @param left 左括号还有几个可以使用 * @param right 右括号还有几个可以使用 * @param list 结果集 */
private void dfs(String str, int left, int right, List<String> list) {
// 在递归终止的时候,直接把它添加到结果集即可
if (left == 0 && right == 0) {
list.add(str);
return;
}
// 剪枝(左括号可以使用的个数严格大于右括号可以使用的个数,剪枝)
if (left > right) {
return;
}
if (left > 0) {
dfs(str+ "(", left - 1, right, list);
}
if (right > 0) {
dfs(str + ")", left, right - 1, list);
}
}
}
边栏推荐
- Build Zabbix Kubernetes cluster monitoring platform
- The most unlucky and the luckiest
- A simple JVM tuning, learn to write it on your resume
- Day20 FPGA 】 【 - block the I2C read and write EEPROM
- EasyCVR接入海康大华设备选择其它集群服务器时,通道ServerID错误该如何解决?
- js 将字符串作为js执行代码使用
- Multi-merchant mall system function disassembly 26 lectures - platform-side distribution settings
- What is third-party payment?
- Interchangeability Measurements and Techniques - Calculation of Deviations and Tolerances, Drawing of Tolerance Charts, Selection of Fits and Tolerance Classes
- 怎么删除语句审计日志?
猜你喜欢

When EasyCVR is connected to the GB28181 device, what is the reason that the device is connected normally but the video cannot be played?

树莓派入门(5)系统备份

QueryDet: Cascading Sparse Query Accelerates Small Object Detection at High Resolution

什么是机器强化学习?原理是什么?

【FPGA】SDRAM

浮点数在内存中的存储方式

Build Zabbix Kubernetes cluster monitoring platform

【FPGA】名词缩写

Description of ESB product development steps under cloud platform

VIT 源码详解
随机推荐
Description of ESB product development steps under cloud platform
console.log alternatives you didn't know about
图解LeetCode——640. 求解方程(难度:中等)
App基本框架搭建丨日志管理 - KLog
What kind of programming trading strategy types can be divided into?
【愚公系列】2022年08月 Go教学课程 035-接口和继承和转换与空接口
程序化交易与主观交易对盈利曲线的影响!
KingbaseES有什么办法,默认不读取sys_catalog下的系统视图?
Interchangeability Measurements and Techniques - Calculation of Deviations and Tolerances, Drawing of Tolerance Charts, Selection of Fits and Tolerance Classes
【FPGA】day20-I2C读写EEPROM
What are port 80 and port 443?What's the difference?
CTO说MySQL单表行数不要超过2000w,为啥?
AI+医疗:使用神经网络进行医学影像识别分析
When EasyCVR is connected to the GB28181 device, what is the reason that the device is connected normally but the video cannot be played?
Typescript study notes | Byte Youth Training Notes
互换性测量技术-几何误差
Interchangeability and Measurement Techniques - Tolerance Principles and Selection Methods
常见布局效果实现方案
The thirteenth day of learning programming
多商户商城系统功能拆解26讲-平台端分销设置