当前位置:网站首页>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;
}
};
边栏推荐
- 剑指 Offer 05. 替换空格
- Palindrome (csp-s-2021-palin) solution
- 26、 File system API (device sharing between applications; directory and file API)
- F - Two Exam(AtCoder Beginner Contest 238)
- After setting up the database and website When you open the app for testing, it shows that the server is being maintained
- Introduction and experience of wazuh open source host security solution
- Codeforces round 712 (Div. 2) d. 3-coloring (construction)
- 二十六、文件系统API(设备在应用间的共享;目录和文件API)
- Educational Codeforces Round 107 (Rated for Div. 2) E. Colorings and Dominoes
- 全排列的代码 (递归写法)
猜你喜欢
Sword finger offer 06 Print linked list from beginning to end
Implement a fixed capacity stack
Sword finger offer 09 Implementing queues with two stacks
剑指 Offer 53 - II. 0~n-1中缺失的数字
Sword finger offer 53 - I. find the number I in the sorted array
AtCoder Grand Contest 013 E - Placing Squares
全国中职网络安全B模块之国赛题远程代码执行渗透测试 //PHPstudy的后门漏洞分析
Sword finger offer 05 Replace spaces
Reader writer model
Acwing 4300. Two operations
随机推荐
One question per day 2047 Number of valid words in the sentence
How many checks does kubedm series-01-preflight have
Zheng Qing 21 ACM is fun. (3) part of the problem solution and summary
884. Uncommon words in two sentences
剑指 Offer 09. 用两个栈实现队列
使用Electron开发桌面应用
Bit mask of bit operation
每日一题-无重复字符的最长子串
Binary search template
Codeforces Round #716 (Div. 2) D. Cut and Stick
AtCoder Grand Contest 013 E - Placing Squares
[practical skills] technical management of managers with non-technical background
Codeforces round 712 (Div. 2) d. 3-coloring (construction)
每日一题-搜索二维矩阵ps二维数组的查找
kubeadm系列-02-kubelet的配置和启动
Time of process
从Dijkstra的图灵奖演讲论科技创业者特点
Wazuh开源主机安全解决方案的简介与使用体验
Light a light with stm32
剑指 Offer 05. 替换空格