Skip to content

Commit cbbad59

Browse files
committed
组合: 括号组合
Change-Id: I8ff4748a33a5bc413283ea1174534cd237a093d7
1 parent ffff02a commit cbbad59

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

go/leetcode/22.括号生成.go

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
* https://leetcode-cn.com/problems/generate-parentheses/description/
77
*
88
* algorithms
9-
* Medium (68.25%)
10-
* Total Accepted: 15K
11-
* Total Submissions: 21.9K
9+
* Medium (70.38%)
10+
* Likes: 385
11+
* Dislikes: 0
12+
* Total Accepted: 24.1K
13+
* Total Submissions: 34.2K
1214
* Testcase Example: '3'
1315
*
1416
* 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
@@ -25,7 +27,26 @@
2527
*
2628
*
2729
*/
30+
31+
func helper(left int, right int, out string, res *[]string) {
32+
if left > right {
33+
return
34+
}
35+
if left == 0 && right == 0 {
36+
*res = append(*res, out) // 复制值
37+
return
38+
}
39+
if left > 0 {
40+
helper(left-1, right, out+"(", res)
41+
}
42+
if right > 0 {
43+
helper(left, right-1, out+")", res)
44+
}
45+
}
46+
2847
func generateParenthesis(n int) []string {
29-
48+
res := []string{}
49+
helper(n, n, "", &res)
50+
return res
3051
}
3152

0 commit comments

Comments
 (0)