Skip to content

Commit 364bc1c

Browse files
aQuaaQua
aQua
authored and
aQua
committed
adding Problem 22
利用递归方法,可以产生结果,但是,由于顺序不对,无法通过测试。
1 parent a051706 commit 364bc1c

File tree

3 files changed

+77
-8
lines changed

3 files changed

+77
-8
lines changed

Algorithms/0022.generate-parentheses/README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
# [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)
22

33
## 题目
4+
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
45

5-
6+
For example, given n = 3, a solution set is:
7+
```
8+
[
9+
"((()))",
10+
"(()())",
11+
"(())()",
12+
"()(())",
13+
"()()()"
14+
]
15+
```
616
## 解题思路
717

818

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,27 @@
11
package Problem0022
22

3+
func generateParenthesis(n int) []string {
4+
if n == 0 {
5+
return []string{""}
6+
}
7+
if n == 1 {
8+
return []string{"()"}
9+
}
10+
11+
return gen(generateParenthesis(n - 1))
12+
}
13+
14+
func gen(strs []string) []string {
15+
res := make([]string, 0, len(strs)*3)
16+
for _, s := range strs {
17+
res = append(res, "("+s+")")
18+
}
19+
for i, s := range strs {
20+
res = append(res, s+"()")
21+
if i != len(strs)-1 {
22+
res = append(res, "()"+s)
23+
}
24+
}
25+
26+
return res
27+
}
Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0022
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,13 +15,13 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
one int
1919
}
2020

2121
// ans 是答案
2222
// one 代表第一个答案
2323
type ans struct {
24-
one string
24+
one []string
2525
}
2626

2727
func Test_Problem0022(t *testing.T) {
@@ -30,17 +30,51 @@ func Test_Problem0022(t *testing.T) {
3030
qs := []question{
3131

3232
question{
33-
para{""},
34-
ans{""},
33+
para{2},
34+
ans{[]string{
35+
"(())",
36+
"()()",
37+
}},
38+
},
39+
40+
question{
41+
para{3},
42+
ans{[]string{
43+
"((()))",
44+
"(()())",
45+
"(())()",
46+
"()(())",
47+
"()()()",
48+
}},
3549
},
36-
50+
51+
question{
52+
para{4},
53+
ans{[]string{
54+
"(((())))",
55+
"((()()))",
56+
"((())())",
57+
"((()))()",
58+
"(()(()))",
59+
"(()()())",
60+
"(()())()",
61+
"(())(())",
62+
"(())()()",
63+
"()((()))",
64+
"()(()())",
65+
"()(())()",
66+
"()()(())",
67+
"()()()()",
68+
}},
69+
},
70+
3771
// 如需多个测试,可以复制上方元素。
3872
}
3973

4074
for _, q := range qs {
4175
a, p := q.ans, q.para
4276
fmt.Printf("~~%v~~\n", p)
4377

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
78+
ast.Equal(a.one, generateParenthesis(p.one), "输入:%v", p)
4579
}
4680
}

0 commit comments

Comments
 (0)