当前位置:网站首页>[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);
}
}
}
边栏推荐
- .NET Custom Middleware
- How to rebuild after pathman_config and pathman_config_params are deleted?
- Get Qt installation information: including installation directory and various macro addresses
- What is ensemble learning in machine learning?
- Homework 8.10 TFTP protocol download function
- Where can machine learning be applied?What is machine learning useful for?
- [C Language] Getting Started
- 机器学习是什么?详解机器学习概念
- The "top pillar" slides, and new growth is extremely difficult to shoulder the heavy responsibility. Is Ali "squatting" to jump higher?
- 机器学习中什么是集成学习?
猜你喜欢

【FPGA】设计思路——I2C协议

console.log alternatives you didn't know about

STC8H development (15): GPIO drive Ci24R1 wireless module

Getting Started with Raspberry Pi (5) System Backup

LeetCode刷题第10天字符串系列之《125回文串验证》

Qnet弱网测试工具操作指南

LeetCode814算题第15天二叉树系列值《814 二叉树剪枝》

EasyCVR接入海康大华设备选择其它集群服务器时,通道ServerID错误该如何解决?

你不知道的 console.log 替代品

LeetCode刷题第17天之《3 无重复字符的最长子串》
随机推荐
uni-app - 获取汉字拼音首字母(根据中文获取拼音首字母)
Interchangeable Measurement Techniques - Geometric Errors
【FPGA】day21-移动平均滤波器
浅析一下期货程序化交易好还是手工单好?
程序化交易的策略类型可以分为哪几种?
MySQL数据库存储引擎以及数据库的创建、修改与删除
程序化交易改变了什么?
使用jackson解析json数据详讲
学编程的第十三天
Which one to choose for mobile map development?
Docker 链接sqlserver时出现en-us is an invalid culture错误解决方案
一文读懂 高性能可预期数据中心网络
Interchangeability Measurements and Techniques - Calculation of Deviations and Tolerances, Drawing of Tolerance Charts, Selection of Fits and Tolerance Classes
元素的BFC属性
Is Redis old?Performance comparison between Redis and Dragonfly
A brief analysis of whether programmatic futures trading or manual order is better?
我的 archinstall 使用手册
MYSQLg advanced ------ clustered and non-clustered indexes
Description of ESB product development steps under cloud platform
【愚公系列】2022年08月 Go教学课程 036-类型断言