Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a82b567

Browse files
author
Shuo
authored
Merge pull request #683 from openset/develop
Add: Generate Parentheses
2 parents 2b6d821 + 9c83491 commit a82b567

File tree

2 files changed

+113
-2
lines changed

2 files changed

+113
-2
lines changed
Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,19 @@
1-
package generate_parentheses
1+
package problem_22
2+
3+
func generateParenthesis(n int) []string {
4+
ans := make([]string, 0)
5+
next("(", 1, 0, n, &ans)
6+
return ans
7+
}
8+
9+
func next(s string, l, r, n int, ans *[]string) {
10+
if l == n && r == n {
11+
*ans = append(*ans, s)
12+
}
13+
if l < n {
14+
next(s+"(", l+1, r, n, ans)
15+
}
16+
if r < l {
17+
next(s+")", l, r+1, n, ans)
18+
}
19+
}
Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,94 @@
1-
package generate_parentheses
1+
package problem_22
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input int
10+
expected []string
11+
}
12+
13+
func TestGenerateParenthesis(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: 3,
17+
expected: []string{
18+
"((()))",
19+
"(()())",
20+
"(())()",
21+
"()(())",
22+
"()()()",
23+
},
24+
},
25+
{
26+
input: 2,
27+
expected: []string{
28+
"(())",
29+
"()()",
30+
},
31+
},
32+
{
33+
input: 1,
34+
expected: []string{"()"},
35+
},
36+
{
37+
input: 0,
38+
expected: []string{},
39+
},
40+
{
41+
input: 5,
42+
expected: []string{
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+
"(())(())()",
69+
"(())()(())",
70+
"(())()()()",
71+
"()(((())))",
72+
"()((()()))",
73+
"()((())())",
74+
"()((()))()",
75+
"()(()(()))",
76+
"()(()()())",
77+
"()(()())()",
78+
"()(())(())",
79+
"()(())()()",
80+
"()()((()))",
81+
"()()(()())",
82+
"()()(())()",
83+
"()()()(())",
84+
"()()()()()",
85+
},
86+
},
87+
}
88+
for _, tc := range tests {
89+
output := generateParenthesis(tc.input)
90+
if !reflect.DeepEqual(output, tc.expected) {
91+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
92+
}
93+
}
94+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /