forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateparentheses.go
34 lines (31 loc) · 900 Bytes
/
generateparentheses.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
}