1
1
//lint:file-ignore U1000 Ignore all unused code
2
2
package main
3
3
4
+ import "slices"
5
+
4
6
func generateParenthesisRecursive (n int ) []string {
5
7
var combinations []string
6
8
currentCombination := make ([]byte , 0 , n * 2 )
@@ -25,31 +27,32 @@ func generateParenthesisRecursive(n int) []string {
25
27
return combinations
26
28
}
27
29
30
+ type combination struct {
31
+ parenthesis []byte
32
+ numLeft int
33
+ numRight int
34
+ }
35
+
28
36
func generateParenthesisIterative (n int ) []string {
29
- var parentheses []string
30
- type state struct {
31
- parenthesis []byte
32
- open int
33
- closed int
34
- }
35
- stack := []state {{[]byte {}, 0 , 0 }}
37
+ var combinations []string
38
+ stack := []combination {{[]byte {}, 0 , 0 }}
36
39
for len (stack ) > 0 {
37
40
current := stack [len (stack )- 1 ]
38
41
stack = stack [:len (stack )- 1 ]
39
- if current .open == n && current .closed == n {
40
- parentheses = append (parentheses , string (current .parenthesis ))
42
+ if current .numLeft == n && current .numRight == n {
43
+ combinations = append (combinations , string (current .parenthesis ))
41
44
continue
42
45
}
43
- if current .open < n {
44
- newParenthesis := append ([] byte {}, current .parenthesis ... )
46
+ if current .numLeft < n {
47
+ newParenthesis := slices . Clone ( current .parenthesis )
45
48
newParenthesis = append (newParenthesis , '(' )
46
- stack = append (stack , state {newParenthesis , current .open + 1 , current .closed })
49
+ stack = append (stack , combination {newParenthesis , current .numLeft + 1 , current .numRight })
47
50
}
48
- if current .open > current .closed {
49
- newParenthesis := append ([] byte {}, current .parenthesis ... )
51
+ if current .numRight < current .numLeft {
52
+ newParenthesis := slices . Clone ( current .parenthesis )
50
53
newParenthesis = append (newParenthesis , ')' )
51
- stack = append (stack , state {newParenthesis , current .open , current .closed + 1 })
54
+ stack = append (stack , combination {newParenthesis , current .numLeft , current .numRight + 1 })
52
55
}
53
56
}
54
- return parentheses
57
+ return combinations
55
58
}
0 commit comments