MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / GenerateParenthesis

Function GenerateParenthesis

strings/generateparentheses/generateparentheses.go:12–34  ·  view source on GitHub ↗
(n int)

Source from the content-addressed store, hash-verified

10import "strings"
11
12func GenerateParenthesis(n int) []string {
13 result := make([]string, 0)
14 maxLen := 2 * n
15 var recursiveComputation func(s []string, left int, right int)
16 recursiveComputation = func(s []string, left int, right int) {
17 if len(s) == maxLen {
18 result = append(result, strings.Join(s, ""))
19 return
20 }
21 if left < n {
22 s = append(s, "(")
23 recursiveComputation(s, left+1, right)
24 s = s[:len(s)-1]
25 }
26 if right < left {
27 s = append(s, ")")
28 recursiveComputation(s, left, right+1)
29 _ = s[:len(s)-1]
30 }
31 }
32 recursiveComputation(make([]string, 0), 0, 0)
33 return result
34}

Callers 1

TestGenerateParenthesisFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestGenerateParenthesisFunction · 0.68