当前位置:网站首页>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;
}
};
边栏推荐
- Use of room database
- Haut OJ 1401: praise energy
- Collection: programming related websites and books
- 从Dijkstra的图灵奖演讲论科技创业者特点
- Alu logic operation unit
- Drawing dynamic 3D circle with pure C language
- 网络工程师考核的一些常见的问题:WLAN、BGP、交换机
- 26、 File system API (device sharing between applications; directory and file API)
- Zzulioj 1673: b: clever characters???
- Pointnet++ learning
猜你喜欢

剑指 Offer 09. 用两个栈实现队列
![[jailhouse article] performance measurements for hypervisors on embedded ARM processors](/img/c0/4843f887f77b80e3b2329e12d28987.png)
[jailhouse article] performance measurements for hypervisors on embedded ARM processors

Chapter 6 data flow modeling - after class exercises
![[article de jailhouse] jailhouse hypervisor](/img/f4/4809b236067d3007fa5835bbfe5f48.png)
[article de jailhouse] jailhouse hypervisor
![[cloud native] record of feign custom configuration of microservices](/img/39/05cf7673155954c90e75a8a2eecd96.jpg)
[cloud native] record of feign custom configuration of microservices

F - Two Exam(AtCoder Beginner Contest 238)

Acwing 4300. Two operations

剑指 Offer 53 - II. 0~n-1中缺失的数字

Codeforces round 712 (Div. 2) d. 3-coloring (construction)

Scope of inline symbol
随机推荐
Cluster script of data warehouse project
读者写者模型
Software test -- 0 sequence
Smart construction site "hydropower energy consumption online monitoring system"
Palindrome (csp-s-2021-palin) solution
6. Logistic model
Binary search template
Codeforces round 712 (Div. 2) d. 3-coloring (construction)
2022年貴州省職業院校技能大賽中職組網絡安全賽項規程
剑指 Offer 53 - II. 0~n-1中缺失的数字
Alu logic operation unit
卷积神经网络——卷积层
Sword finger offer 09 Implementing queues with two stacks
Use of room database
EOJ 2021.10 E. XOR tree
数仓项目的集群脚本
Talking about JVM (frequent interview)
Introduction to convolutional neural network
剑指 Offer 53 - I. 在排序数组中查找数字 I
Solution to the palindrome string (Luogu p5041 haoi2009)