-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
88 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} | ||
} |