Skip to content

Commit

Permalink
Add problem 9 of chapter 8
Browse files Browse the repository at this point in the history
  • Loading branch information
motomux committed Feb 25, 2017
1 parent 5666eba commit b27b2f0
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
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 main

// 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 main

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)
}
})
}
}

0 comments on commit b27b2f0

Please sign in to comment.