Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add problem 9 of chapter 8 #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add problem 9 of chapter 8
  • Loading branch information
motomux committed Feb 25, 2017
commit 70c2a45b0a057db654b3ed82839a6edc709b10c7
32 changes: 32 additions & 0 deletions src/chapter8/problem9.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package chapter8

// Parens returns all valid parentheses by given number of pairs
func Parens(num int) []string {
var (
res []string
bs []byte
)

ParensR(num, 0, 0, bs, &res)

return res
}

// ParensR adds valid parentheses with recursion
func ParensR(num, leftCnt, rightCnt int, bs []byte, res *[]string) {
if num < leftCnt || num < rightCnt {
return
}
if num == leftCnt && num == rightCnt {
*res = append(*res, string(bs))
return
}

if leftCnt < num {
ParensR(num, leftCnt+1, rightCnt, append(bs, '('), res)
}

if rightCnt < num && rightCnt < leftCnt {
ParensR(num, leftCnt, rightCnt+1, append(bs, ')'), res)
}
}
56 changes: 56 additions & 0 deletions src/chapter8/problem9_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package chapter8

import (
"reflect"
"testing"
)

func TestParens(t *testing.T) {
tests := map[string]struct {
in int
out []string
}{
"Input is -1": {
in: -1,
out: []string(nil),
},
"Input is 0": {
in: 0,
out: []string{
"",
},
},
"Input is 1": {
in: 1,
out: []string{
"()",
},
},
"Input is 2": {
in: 2,
out: []string{
"(())",
"()()",
},
},
"Input is 3": {
in: 3,
out: []string{
"((()))",
"(()())",
"(())()",
"()(())",
"()()()",
},
},
}

for k, test := range tests {
t.Run(k, func(t *testing.T) {
out := Parens(test.in)
if !reflect.DeepEqual(out, test.out) {
t.Errorf("actual=%+v expected=%+v", out, test.out)
}
})
}
}