当前位置:网站首页>[record of question brushing] 22. bracket generation
[record of question brushing] 22. bracket generation
2022-07-26 20:27:00 【InfoQ】
One 、 Title Description
source :
Power button (LeetCode)
Numbers n Represents the logarithm of the generated bracket , Please design a function , Used to be able to generate all possible and
Effective
Bracket combination .
Example 1:
Input :n = 3
Output :["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input :n = 1
Output :["()"]
Tips :
- 1 <= n <= 8
II. Train of thought analysis
backtracking about
n Parenthesis , There will be
n individual
( and
n individual
) altogether
2n Characters
We use DFS To recursively produce all sequence cases , To reduce the number of recursions , Every recursive time
- The number of left parentheses shall not be greater than
n, We can put a left bracket .
- If the number of right brackets is less than the number of left brackets , Let's put a right parenthesis . To ensure that our parentheses are paired and valid .
3、 ... and 、 Code implementation
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
dfs(res, new StringBuilder(), 0, 0, n);
return res;
}
public void dfs(List<String> ans, StringBuilder cur, int l, int r, int len) {
if (cur.length() == len * 2) {
ans.add(cur.toString());
return;
}
if (l < len) {
cur.append('(');
dfs(ans, cur, l + 1, r, len);
cur.deleteCharAt(cur.length() - 1);
}
if (r < l) {
cur.append(')');
dfs(ans, cur, l, r + 1, len);
cur.deleteCharAt(cur.length() - 1);
}
}
}
Complexity analysis
- Time complexity : The typical Cartland number problem , The complexity is
nNumber of left parentheses .
- Spatial complexity :
Running results

summary
This problem is to traverse all n The string generated by the combination of parentheses , Then verify the valid brackets .
But these will produce more inconformity . So we can follow the rules , Further narrow the scope , Let it only recursively produce the results we need .
边栏推荐
猜你喜欢
随机推荐
Cookie和Session
使用请求头认证来测试需要授权的 API 接口
Principle and application of one click login of local number (glory Collection Edition)
如何优雅地赞美他人?不妨尝试下这几种方式
Servlet
MySQL InnoDB engine (V)
Vite configuration eslint specification code
Ue5 editor slate quick start [opening]
How to implement an asynchronous task queue system that can handle massive data (supreme Collection Edition)
QT信号与槽连接(松耦合)
ES6 method & Class array into real array & method of judging array
This points to the simplest rule remember it
shell脚本基础编程命令
2000 words to help you master anti shake and throttling
Exchange 2010 SSL证书安装文档
Typescrip异步函数Promise使用
聊天软件项目开发2
GBase学习-安装GBase 8a MPP Cluster V95
cv2.resize()
Servlet









