-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path22_generate_parentheses_test.go
68 lines (53 loc) · 1.09 KB
/
22_generate_parentheses_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package _6_backtracking
import (
"github.com/smartystreets/goconvey/convey"
"strings"
"testing"
)
// 括号生成 https://leetcode.cn/problems/generate-parentheses/
func TestGenerateParenthesis(t *testing.T) {
convey.Convey("括号生成 ", t, func() {
testCase := []struct {
input struct {
n int
}
target []string
}{
{
struct {
n int
}{n: 3}, []string{"((()))", "(()())", "(())()", "()(())", "()()()"},
},
{
struct {
n int
}{n: 1}, []string{"()"},
},
}
for _, tst := range testCase {
rsp := generateParenthesis(tst.input.n)
convey.So(rsp, convey.ShouldEqual, tst.target)
}
})
}
func generateParenthesis(n int) []string {
total := n * 2
ans := make([]string, 0)
path := make([]string, total)
var dfs func(i int, left int)
dfs = func(i int, left int) {
if i == total {
ans = append(ans, strings.Join(path, ""))
}
if left < n { // 说明还可以选择左括号
path[i] = "("
dfs(i+1, left+1)
}
if i-left < left { // 右括号小于左括号
path[i] = ")"
dfs(i+1, left)
}
}
dfs(0, 0)
return ans
}