当前位置:网站首页>[Likou] 22. Bracket generation
[Likou] 22. Bracket generation
2022-08-11 03:58: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);
}
}
}
边栏推荐
- Leetcode 450. 删除二叉搜索树中的节点
- C language recv() function, recvfrom() function, recvmsg() function
- Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
- FTP错误代码列表
- The impact of programmatic trading and subjective trading on the profit curve!
- 【愚公系列】2022年08月 Go教学课程 035-接口和继承和转换与空接口
- 【FPGA】SDRAM
- MYSQLg advanced ------ return table
- Echart地图的省级,以及所有地市级下载与使用
- MYSQLg advanced ------ clustered and non-clustered indexes
猜你喜欢

Redis老了吗?Redis与Dragonfly性能比较

EasyCVR接入GB28181设备时,设备接入正常但视频无法播放是什么原因?

Differences and connections between distributed and clustered

QueryDet:级联稀疏query加速高分辨率下的小目标检测

What is Machine Reinforcement Learning?What is the principle?

Day20 FPGA 】 【 - block the I2C read and write EEPROM

LeetCode刷题第16天之《239滑动窗口最大值》

【FPGA】day22-SPI协议回环

Which one to choose for mobile map development?

The custom of the C language types -- -- -- -- -- - structure
随机推荐
Leetcode 108. 将有序数组转换为二叉搜索树
Enter the starting position, the ending position intercepts the linked list
【C语言】入门
What are port 80 and port 443?What's the difference?
常见布局效果实现方案
一文读懂 高性能可预期数据中心网络
Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
Multi-serial port RS485 industrial gateway BL110
【FPGA】SDRAM
uni-app - 获取汉字拼音首字母(根据中文获取拼音首字母)
【FPGA】day22-SPI协议回环
Description of ESB product development steps under cloud platform
【FPGA】day18-ds18b20实现温度采集
MYSQLg advanced ------ return table
Get Qt installation information: including installation directory and various macro addresses
En-us is an invalid culture error solution when Docker links sqlserver
【FPGA】day21- moving average filter
Callable实现多线程
[ADI low-power 2k code] Based on ADuCM4050, ADXL363, TMP75 acceleration, temperature detection and serial port printing, buzzer playing music (lone warrior)
【FPGA】设计思路——I2C协议