当前位置:网站首页>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:代码是照着别人的敲得,其实还是不太理解递归,恼火
边栏推荐
猜你喜欢

微服务【同步和异步通讯详解】第6章

【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price

温度响应性纳米水凝胶光子品体/纤维素修饰荧光水凝胶/载脂质体水凝胶的制备方法

Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)

D-Biotinol Involved by Biotin, CAS No: 53906-36-8 Specific Properties Description

Xi'an biotin-tetrapolyethylene glycol-amide-4phenol light yellow semi-solid

What should I do if there is no sound after reinstalling the system in win10?

FITC标记生物素(FITC-生物素|CAS:134759-22-1)有哪些知识了?

为什么字符串一旦创建就不可以改变?

What do you know about FITC-labeled biotin (FITC-biotin|CAS: 134759-22-1)?
随机推荐
基于Web的疫情隔离区订餐系统
【kali-密码攻击】(5.1.2)密码在线破解:Medusa
基于SSM实现手机销售商城系统
头脑风暴:单词拆分
What should I do if there is no sound after reinstalling the system in win10?
ASEMI整流桥GBJ1010参数,GBJ1010规格,GBJ1010封装
【报错】ModuleNotFoundError: No module named ‘scp‘
y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)
数据的存储——C语言
数据建模已死,真的吗?
How to add control panel to right click menu in win7
C language structure, function and pointer exercise (simple address book)
高校就业管理系统设计与实现
JDBC数据库连接池练习题
Data storage - the C language
宽带由20M换为100M
-Vector Dot Product-
使用 GoogleTest 框架对 C 代码进行单元测试
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
CAS:183896-00-6 (Biotin-PEG3-C3-NH2) PEG衍生物