-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
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
55 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,34 @@ | ||
// generateparenthesesgo | ||
// description: Generate Parentheses | ||
// details: | ||
// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. | ||
// author(s) [red_byte](https://github.com/i-redbyte) | ||
// see generateparentheses_test.go | ||
|
||
package generateparentheses | ||
|
||
import "strings" | ||
|
||
func GenerateParenthesis(n int) []string { | ||
result := make([]string, 0) | ||
maxLen := 2 * n | ||
var recursiveComputation func(s []string, left int, right int) | ||
recursiveComputation = func(s []string, left int, right int) { | ||
if len(s) == maxLen { | ||
result = append(result, strings.Join(s, "")) | ||
return | ||
} | ||
if left < n { | ||
s = append(s, "(") | ||
recursiveComputation(s, left+1, right) | ||
s = s[:len(s)-1] | ||
} | ||
if right < left { | ||
s = append(s, ")") | ||
recursiveComputation(s, left, right+1) | ||
_ = s[:len(s)-1] | ||
} | ||
} | ||
recursiveComputation(make([]string, 0), 0, 0) | ||
return result | ||
} |
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,21 @@ | ||
// generateparentheses_test.go | ||
// description: Generate Parentheses | ||
// author(s) [red_byte](https://github.com/i-redbyte) | ||
// see generateparentheses.go | ||
|
||
package generateparentheses | ||
|
||
import "testing" | ||
|
||
func TestGenerateParenthesis(t *testing.T) { | ||
t.Run("GenerateParenthesis", func(t *testing.T) { | ||
result := GenerateParenthesis(3) | ||
t.Log(result) | ||
exp := []string{"((()))", "(()())", "(())()", "()(())", "()()()"} | ||
for i, v := range result { | ||
if v != exp[i] { | ||
t.Errorf("Wrong result! Expected:%s, returned:%s ", result[i], exp[i]) | ||
} | ||
} | ||
}) | ||
} |