当前位置:网站首页>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:代码是照着别人的敲得,其实还是不太理解递归,恼火
边栏推荐
猜你喜欢
随机推荐
c语言文件基本操作总结
pytest:如何在测试中编写和报告断言
How to activate the payment function on WeChat official account?
头脑风暴:单词拆分
-Pickling peanuts-
使用 apxs 构建和安装 Apache 扩展共享对象模块
Web性能测试模型小结
使用 GoogleTest 框架对 C 代码进行单元测试
How to turn off system protection in Win11?How to turn off the system protection restore function?
【ROS2原理10】Interface数据的规定
Win11怎么关闭系统保护功能?系统保护还原功能怎么关闭?
20220808-一些想法
Prometeus 2.31.0 新特性
flask——请求、响应、请求扩展、session、闪现、蓝图、g对象、flask-session
FITC标记生物素(FITC-生物素|CAS:134759-22-1)有哪些知识了?
Leetcode81. 搜索旋转排序数组 II
Leetcode80. 删除有序数组中的重复项 II
win10重装系统后没声音怎么办?
微信小程序tab切换时保存checkbox状态
3.4 - 编译与解释 3.5 - 编译过程 3.8 - 文法