Skip to content

Commit 7246e66

Browse files
committed
refactor generate parenthesis
1 parent bdd9f8c commit 7246e66

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

go/generate_parentheses.go

+19-16
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
//lint:file-ignore U1000 Ignore all unused code
22
package main
33

4+
import "slices"
5+
46
func generateParenthesisRecursive(n int) []string {
57
var combinations []string
68
currentCombination := make([]byte, 0, n*2)
@@ -25,31 +27,32 @@ func generateParenthesisRecursive(n int) []string {
2527
return combinations
2628
}
2729

30+
type combination struct {
31+
parenthesis []byte
32+
numLeft int
33+
numRight int
34+
}
35+
2836
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}}
3639
for len(stack) > 0 {
3740
current := stack[len(stack)-1]
3841
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))
4144
continue
4245
}
43-
if current.open < n {
44-
newParenthesis := append([]byte{}, current.parenthesis...)
46+
if current.numLeft < n {
47+
newParenthesis := slices.Clone(current.parenthesis)
4548
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})
4750
}
48-
if current.open > current.closed {
49-
newParenthesis := append([]byte{}, current.parenthesis...)
51+
if current.numRight < current.numLeft {
52+
newParenthesis := slices.Clone(current.parenthesis)
5053
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})
5255
}
5356
}
54-
return parentheses
57+
return combinations
5558
}

0 commit comments

Comments
 (0)