LeetCode/exercises/dynamic-programming/22-generate-parenthesis/golang/main.go

54 lines
990 B
Go
Raw Normal View History

2021-08-03 12:42:59 -05:00
package main
2021-08-08 10:53:32 -05:00
import (
"strings"
"container/list"
)
2021-08-03 12:42:59 -05:00
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
()()(); (())(); ((()));
()(());
(()())
Input: n = 1
Output: ["()"]
()(); (())
Constraints:
1 <= n <= 8
*/
2021-08-08 10:53:32 -05:00
func rec(input []string, left int, right int, n int, ans *[]string) {
2021-08-03 12:42:59 -05:00
2021-08-08 10:53:32 -05:00
if len(input) == 2*n {
*ans = append(*ans, strings.Join(input, ""))
return
2021-08-03 12:42:59 -05:00
}
2021-08-08 10:53:32 -05:00
if left < n {
input = append(input, "(")
rec(input, left+1, right, n, ans)
input = input[0:len(input)-1]
2021-08-03 12:42:59 -05:00
}
2021-08-08 10:53:32 -05:00
if right < left {
input = append(input, ")")
rec(input, left, right+1, n, ans)
input = input[0:len(input)-1]
2021-08-03 12:42:59 -05:00
}
}
2021-08-08 10:53:32 -05:00
func generateParenthesis(n int) []string {
var output = make([]string, 2*n)
var input = make([]string, 2*n)
rec(input, 0, 0, n, &output)
return output
}
2021-08-03 12:42:59 -05:00
func main() {
2021-08-08 10:53:32 -05:00
generateParenthesis(3)
2021-08-03 12:42:59 -05:00
}