Skip to content

Commit

Permalink
feat: generate parentheses (#361)
Browse files Browse the repository at this point in the history
  • Loading branch information
i-redbyte authored Oct 1, 2021
1 parent 420ddd6 commit 28ede29
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
34 changes: 34 additions & 0 deletions strings/generateparentheses/generateparentheses.go
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
}
21 changes: 21 additions & 0 deletions strings/generateparentheses/generateparentheses_test.go
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])
}
}
})
}

0 comments on commit 28ede29

Please sign in to comment.