当前位置:网站首页>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;
}
};
边栏推荐
- Warning using room database: schema export directory is not provided to the annotation processor so we cannot export
- 每日一题-搜索二维矩阵ps二维数组的查找
- 全排列的代码 (递归写法)
- After setting up the database and website When you open the app for testing, it shows that the server is being maintained
- Add level control and logger level control of Solon logging plug-in
- 读者写者模型
- Transform optimization problems into decision-making problems
- 常见的最优化方法
- Graduation project of game mall
- 剑指 Offer 35.复杂链表的复制
猜你喜欢

剑指 Offer 53 - I. 在排序数组中查找数字 I

剑指 Offer 58 - II. 左旋转字符串

F - Two Exam(AtCoder Beginner Contest 238)

读者写者模型

Introduction et expérience de wazuh open source host Security Solution

Sword finger offer 05 Replace spaces

剑指 Offer 05. 替换空格

Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module

Graduation project of game mall

CF1634E Fair Share
随机推荐
Csp-j-2020-excellent split multiple solutions
Codeforces Round #716 (Div. 2) D. Cut and Stick
Configuration and startup of kubedm series-02-kubelet
One question per day 1765 The highest point in the map
数仓项目的集群脚本
Dichotomy, discretization, etc
7. Processing the input of multidimensional features
Web APIs DOM node
挂起等待锁 vs 自旋锁(两者的使用场合)
【实战技能】非技术背景经理的技术管理
Daily question 1984 Minimum difference in student scores
Daily question 1342 Number of operations to change the number to 0
Haut OJ 2021 freshmen week II reflection summary
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
【Jailhouse 文章】Performance measurements for hypervisors on embedded ARM processors
个人开发的渗透测试工具Satania v1.2更新
剑指 Offer 06.从头到尾打印链表
R语言【数据集的导入导出】
YOLOv5-Shufflenetv2
Control unit