parent
9790a5d6c5
commit
68eca139ca
@ -0,0 +1,25 @@
|
||||
package genparen
|
||||
|
||||
func iter(result *[]string, current string, left int, right int) {
|
||||
if left == 0 && right == 0 {
|
||||
*result = append(*result, current)
|
||||
return
|
||||
}
|
||||
|
||||
if left > 0 {
|
||||
iter(result, current+"(", left-1, right)
|
||||
}
|
||||
if right > left {
|
||||
iter(result, current+")", left, right-1)
|
||||
}
|
||||
}
|
||||
|
||||
func generateParenthesis(n int) []string {
|
||||
result := make([]string, 0, n^2)
|
||||
iter(&result, "", n, n)
|
||||
return result
|
||||
}
|
||||
|
||||
func Gen(n int) []string {
|
||||
return generateParenthesis(n)
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package genparen_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.jxs.me/leetgo/genparen"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEmpty(t *testing.T) {
|
||||
require.Equal(t, []string{""}, genparen.Gen(0))
|
||||
}
|
||||
|
||||
func TestOne(t *testing.T) {
|
||||
require.Equal(t, []string{"()"}, genparen.Gen(1))
|
||||
}
|
||||
|
||||
func TestTwo(t *testing.T) {
|
||||
require.Equal(t, []string{"(())", "()()"}, genparen.Gen(2))
|
||||
}
|
||||
|
||||
func TestThree(t *testing.T) {
|
||||
require.Equal(t, []string{"((()))", "(()())", "(())()", "()(())", "()()()"}, genparen.Gen(3))
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
22. Generate Parentheses
|
||||
Medium
|
||||
|
||||
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
|
||||
|
||||
|
Loading…
Reference in new issue