[nb] Commit

This commit is contained in:
Aerex 2021-08-08 10:53:32 -05:00
parent a8716f9734
commit f9c2c88398
3 changed files with 78 additions and 43 deletions

View File

@ -1,4 +1,8 @@
package main package main
import (
"strings"
"container/list"
)
/* /*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1: Example 1:
@ -20,37 +24,30 @@ Constraints:
1 <= n <= 8 1 <= n <= 8
*/ */
func rec(int index, dp map[string]string) { func rec(input []string, left int, right int, n int, ans *[]string) {
if len(input) == 2*n {
*ans = append(*ans, strings.Join(input, ""))
return
}
if left < n {
input = append(input, "(")
rec(input, left+1, right, n, ans)
input = input[0:len(input)-1]
}
if right < left {
input = append(input, ")")
rec(input, left, right+1, n, ans)
input = input[0:len(input)-1]
}
} }
func generateParenthesis(n int) []string {
func generateParenthesis(n int)[] string { var output = make([]string, 2*n)
var input = make([]string, 2*n)
if n == 1 { rec(input, 0, 0, n, &output)
return []string{"()"} return output
}
if n == 2 {
return []string{"()()", "(())"}
}
var output = make([]string, 0)
var dp = map[string]string{}
var start_string string = ""
for i := 0; i < n - 1; i++ {
start_string = start_string + "()"
out_arr = a
}
output = append(output, start_string)
for i := 1; i < n - 1; i++ {
result := rec(i+1, dp) + rec(i-1)
}
} }
func main() { func main() {
generateParenthesis(3)
} }

View File

@ -1,17 +1,30 @@
function generateParenthesis(n) { function generateParenthesis(n) {
if (n == 1) { const output = []
return ['()']; const rec = (input = [], left = 0, right = 0) => {
} if (input.length === 2*n) {
output.push(input.join(''));
console.log('sol');
return
}
if (left < n) {
input.push('(');
console.log(input.join('') + ' l=' + left + ' r=' + right)
rec(input, left+1, right);
console.log('back left');
input.pop();
}
if (n == 2) { if (right < left) {
return ['()()', '(())']; input.push(')');
} console.log(input.join('') + ' l=' + left + ' r=' + right)
rec(input, left, right+1);
const input = []; console.log('back right l=' + left);
for (i = 0; i < n; i++) { input.pop();
input.push('()'); console.log(input.join('') + ' l=' + left + ' r=' + right)
} }
};
for(i = 0; i < n; i++; i++) { rec();
} return output;
} }
console.log(generateParenthesis(3));

View File

@ -0,0 +1,25 @@
from typing import List
# ()()()
# (())()
# ((()))
# ()(())
# (()())
def generateParenthesis(n: int) -> List[str]:
ans = []
def backtrack(S = [], left = 0, right = 0):
if len(S) == 2 * n:
ans.append("".join(S))
return
if left < n:
S.append("(")
backtrack(S, left+1, right)
S.pop()
if right < left:
S.append(")")
backtrack(S, left, right+1)
S.pop()
backtrack()
return ans
generateParenthesis(3)