[nb] Sync

This commit is contained in:
2022-02-20 21:55:27 -06:00
parent f9c2c88398
commit 3551467ef9
17 changed files with 38 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
package main
import (
"strings"
"container/list"
)
/*
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
*/
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 {
var output = make([]string, 2*n)
var input = make([]string, 2*n)
rec(input, 0, 0, n, &output)
return output
}
func main() {
generateParenthesis(3)
}

View File

@@ -0,0 +1,30 @@
function generateParenthesis(n) {
const output = []
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 (right < left) {
input.push(')');
console.log(input.join('') + ' l=' + left + ' r=' + right)
rec(input, left, right+1);
console.log('back right l=' + left);
input.pop();
console.log(input.join('') + ' l=' + left + ' r=' + right)
}
};
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)