Skip to content

Commit 2f6293d

Browse files
Create 22. 括号生成.md
1 parent 3a120df commit 2f6293d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#### 22. 括号生成
2+
3+
难度:中等
4+
5+
---
6+
7+
数字 `n` 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 **有效的** 括号组合。
8+
9+
**示例 1:**
10+
11+
```
12+
输入:n = 3
13+
输出:["((()))","(()())","(())()","()(())","()()()"]
14+
```
15+
16+
**示例 2:**
17+
18+
```
19+
输入:n = 1
20+
输出:["()"]
21+
```
22+
23+
**提示:**
24+
25+
* `1 <= n <= 8`
26+
27+
---
28+
29+
深度优先搜索:
30+
31+
用两个变量分别记录左/右括号剩余的数量,显然,左括号剩余的数量一定不能大于右括号剩余的数量。
32+
33+
只要左括号剩余的数量大于零,就要将该数量减一并继续递归。只有当右括号剩余的数量大于左括号剩余的数量时,才继续递归。
34+
35+
```Go
36+
func generateParenthesis(n int) []string {
37+
res := []string{}
38+
var dfs func(num1, num2 int, s string)
39+
dfs = func(num1, num2 int, s string) {
40+
if len(s) == 2 * n {
41+
res = append(res, s)
42+
return
43+
}
44+
if num1 > 0 {
45+
dfs(num1 - 1, num2, s + "(")
46+
}
47+
if num1 < num2 {
48+
dfs(num1, num2 - 1, s + ")")
49+
}
50+
}
51+
dfs(n, n, "")
52+
return res
53+
}
54+
55+
56+
```

0 commit comments

Comments
 (0)