当前位置:网站首页>22.括号生成
22.括号生成
2022-08-10 00:32:00 【等风来】
题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:
输入:n = 1
输出:[“()”]
代码
//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res=new ArrayList<>();
if (n <= 0) return res;
dfs(n, "", res, 0, 0);
return res;
}
private void dfs(int n, String path, List<String> res, int open, int close){
if(open > n || open < close) return;
if(path.length() == 2 * n){
res.add(path);
return;
}
dfs(n, path+"(", res, open + 1, close);
dfs(n, path+")", res, open, close + 1);
}
public static void main(String[] args) {
System.out.println(new Solution().generateParenthesis(2));
}
}
笔记
剪枝策略
所谓的剪枝策略就是在生成树的过程中避免生成一些无意义的分支,比如上边的 if(open > n || open < close) return;
回溯
所谓的回溯就是在递归到递归出口时,往回走的过程
ps:代码是照着别人的敲得,其实还是不太理解递归,恼火
边栏推荐
- FITC标记生物素(FITC-生物素|CAS:134759-22-1)有哪些知识了?
- How to add control panel to right click menu in win7
- R语言使用glm函数构建逻辑回归模型(logistic)、使用subgroupAnalysis函数进行亚组分析并可视化森林图
- MySQL最大连接数限制如何修改
- 最高月薪15K,谁有历经千辛万苦的意志,谁就能收获属于自己的成功~
- 基于Web的疫情隔离区订餐系统
- Qt的pro文件递归搜寻添加文件
- 惊掉你下巴,程序员编码竟然可以被 996 指数化
- R语言使用cox函数构建生存分析回归模型、使用subgroupAnalysis进行亚组分析并可视化森林图
- 【Django】缓存
猜你喜欢
flask——请求、响应、请求扩展、session、闪现、蓝图、g对象、flask-session
How to add control panel to right click menu in win7
Leetcode82. 删除排序链表中的重复元素 II
C language pointer practice questions
Next.js获取路由参数及styled-jsx 的使用
2022金九银十工作潮,怎么样才能成功跳槽面试拿到高薪呢?
CAS:183896-00-6 (Biotin-PEG3-C3-NH2) PEG衍生物
商业模式及其 SubDAO 深入研究
Quick responsiveness intelligent/smart responsiveness of polyethylene glycol type nano/reduction response hydrogels research and preparation
Docker interview question 2--get the number of database connections and docker-compose
随机推荐
03|流程控制
Docker interview question 2--get the number of database connections and docker-compose
阿里云混合云管理平台多Region架构
基于SSM实现手机销售商城系统
Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)
Are the numbers entered symmetrical?
走出迷宫的最少步数2
Web性能测试模型小结
Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
c语言结构体、函数以及指针练习(简单通讯录)
-Chess game-
为什么字符串一旦创建就不可以改变?
Data storage - the C language
【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price
c语言指针练习题
-红与黑-
Redis redisTemplate.execute 执行锁
365 days challenge LeetCode1000 questions - Day 052 Step by step summation to get the minimum value of positive numbers Greedy
初步认识对象
头脑风暴:单词拆分