当前位置:网站首页>leetcode-22:括号生成
leetcode-22:括号生成
2022-07-05 05:46:00 【菊头蝙蝠】
题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
解题
如果直接暴力回溯,让’('和‘)'自由组合,然后判断括号有效性,这样做,复杂度会比较高。
因此可以在直接通过一些判断条件,使得生成的括号是有效的。
方法一:回溯
通过open ,close来计数 开闭括号数量,保证close<open才会加入闭括号,以此来保证生成的括号的有效性。
class Solution {
public:
string path;
vector<string> res;
void dfs(int open,int close,int n){
if(path.size()==n*2){
res.push_back(path);
return;
}
if(open<n){
path.push_back('(');
dfs(open+1,close,n);
path.pop_back();
}
if(close<open){
path.push_back(')');
dfs(open,close+1,n);
path.pop_back();
}
}
vector<string> generateParenthesis(int n) {
dfs(0,0,n);
return res;
}
};
边栏推荐
- Sword finger offer 04 Search in two-dimensional array
- wordpress切换页面,域名变回了IP地址
- Personal developed penetration testing tool Satania v1.2 update
- Control unit
- CF1634E Fair Share
- “磐云杯”中职网络安全技能大赛A模块新题
- 游戏商城毕业设计
- 卷积神经网络——卷积层
- Talking about JVM (frequent interview)
- Daily question 1984 Minimum difference in student scores
猜你喜欢
Sword finger offer 58 - ii Rotate string left
Dynamic planning solution ideas and summary (30000 words)
Sword finger offer 04 Search in two-dimensional array
Brief introduction to tcp/ip protocol stack
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
Implement an iterative stack
[practical skills] how to do a good job in technical training?
Implement a fixed capacity stack
Sword finger offer 09 Implementing queues with two stacks
The connection and solution between the shortest Hamilton path and the traveling salesman problem
随机推荐
Scope of inline symbol
YOLOv5-Shufflenetv2
全国中职网络安全B模块之国赛题远程代码执行渗透测试 //PHPstudy的后门漏洞分析
CF1634 F. Fibonacci Additions
Alu logic operation unit
每日一题-搜索二维矩阵ps二维数组的查找
Codeforces Round #732 (Div. 2) D. AquaMoon and Chess
【实战技能】如何做好技术培训?
注解与反射
Daily question - Search two-dimensional matrix PS two-dimensional array search
Wazuh开源主机安全解决方案的简介与使用体验
常见的最优化方法
Software test -- 0 sequence
读者写者模型
1996. number of weak characters in the game
Kubedm series-00-overview
2022年貴州省職業院校技能大賽中職組網絡安全賽項規程
Wazuh開源主機安全解决方案的簡介與使用體驗
How many checks does kubedm series-01-preflight have
Daily question 1984 Minimum difference in student scores