diff --git a/problems/generate-parentheses/generate_parentheses.go b/problems/generate-parentheses/generate_parentheses.go index 96f609a0d..880fbf2ca 100644 --- a/problems/generate-parentheses/generate_parentheses.go +++ b/problems/generate-parentheses/generate_parentheses.go @@ -1 +1,19 @@ -package generate_parentheses +package problem_22 + +func generateParenthesis(n int) []string { + ans := make([]string, 0) + next("(", 1, 0, n, &ans) + return ans +} + +func next(s string, l, r, n int, ans *[]string) { + if l == n && r == n { + *ans = append(*ans, s) + } + if l < n { + next(s+"(", l+1, r, n, ans) + } + if r < l { + next(s+")", l, r+1, n, ans) + } +} diff --git a/problems/generate-parentheses/generate_parentheses_test.go b/problems/generate-parentheses/generate_parentheses_test.go index 96f609a0d..5571c21b4 100644 --- a/problems/generate-parentheses/generate_parentheses_test.go +++ b/problems/generate-parentheses/generate_parentheses_test.go @@ -1 +1,94 @@ -package generate_parentheses +package problem_22 + +import ( + "reflect" + "testing" +) + +type caseType struct { + input int + expected []string +} + +func TestGenerateParenthesis(t *testing.T) { + tests := [...]caseType{ + { + input: 3, + expected: []string{ + "((()))", + "(()())", + "(())()", + "()(())", + "()()()", + }, + }, + { + input: 2, + expected: []string{ + "(())", + "()()", + }, + }, + { + input: 1, + expected: []string{"()"}, + }, + { + input: 0, + expected: []string{}, + }, + { + input: 5, + expected: []string{ + "((((()))))", + "(((()())))", + "(((())()))", + "(((()))())", + "(((())))()", + "((()(())))", + "((()()()))", + "((()())())", + "((()()))()", + "((())(()))", + "((())()())", + "((())())()", + "((()))(())", + "((()))()()", + "(()((())))", + "(()(()()))", + "(()(())())", + "(()(()))()", + "(()()(()))", + "(()()()())", + "(()()())()", + "(()())(())", + "(()())()()", + "(())((()))", + "(())(()())", + "(())(())()", + "(())()(())", + "(())()()()", + "()(((())))", + "()((()()))", + "()((())())", + "()((()))()", + "()(()(()))", + "()(()()())", + "()(()())()", + "()(())(())", + "()(())()()", + "()()((()))", + "()()(()())", + "()()(())()", + "()()()(())", + "()()()()()", + }, + }, + } + for _, tc := range tests { + output := generateParenthesis(tc.input) + if !reflect.DeepEqual(output, tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}