当前位置:网站首页>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;
}
};
边栏推荐
- Daily question 1984 Minimum difference in student scores
- 网络工程师考核的一些常见的问题:WLAN、BGP、交换机
- [cloud native] record of feign custom configuration of microservices
- 卷积神经网络简介
- [jailhouse article] jailhouse hypervisor
- 26、 File system API (device sharing between applications; directory and file API)
- Software test -- 0 sequence
- shared_ Repeated release heap object of PTR hidden danger
- 884. Uncommon words in two sentences
- Configuration and startup of kubedm series-02-kubelet
猜你喜欢

YOLOv5-Shufflenetv2

CF1637E Best Pair

sync. Interpretation of mutex source code

Educational Codeforces Round 116 (Rated for Div. 2) E. Arena

In this indifferent world, light crying

【云原生】微服务之Feign自定义配置的记录

7. Processing the input of multidimensional features

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

Sword finger offer 06 Print linked list from beginning to end

Chapter 6 data flow modeling - after class exercises
随机推荐
游戏商城毕业设计
Palindrome (csp-s-2021-palin) solution
[jailhouse article] jailhouse hypervisor
Software test -- 0 sequence
[article de jailhouse] jailhouse hypervisor
Cluster script of data warehouse project
A problem and solution of recording QT memory leakage
Sword finger offer 05 Replace spaces
R language [import and export of dataset]
The sum of the unique elements of the daily question
剑指 Offer 05. 替换空格
Annotation and reflection
F - Two Exam(AtCoder Beginner Contest 238)
Sword finger offer 58 - ii Rotate string left
High precision subtraction
【云原生】微服务之Feign自定义配置的记录
Sword finger offer 06 Print linked list from beginning to end
卷积神经网络简介
Individual game 12
CCPC Weihai 2021m eight hundred and ten thousand nine hundred and seventy-five