Skip to content

Instantly share code, notes, and snippets.

@selcukcihan
Created December 8, 2022 12:35
Show Gist options
  • Save selcukcihan/d0d3612b8d4b644ecc63633cddf52a10 to your computer and use it in GitHub Desktop.
Save selcukcihan/d0d3612b8d4b644ecc63633cddf52a10 to your computer and use it in GitHub Desktop.
function recurse(current: string, remaining: { left: number; right: number; }) {
if (remaining.left === 0 && remaining.right === 0) {
return [current]
} else {
let result = []
// check if we can go with a "("
if (remaining.left) {
let balance = 0
for (const s of current) {
if (s === '(') {
balance++
} else {
balance--
}
}
if (balance + 1 <= remaining.right) {
result.push(...recurse(current + '(', { left: remaining.left - 1, right: remaining.right }))
}
}
// check if we can go with a ")"
if (remaining.right) {
let balance = 0
for (const s of current) {
if (s === ')') {
balance++
} else {
balance--
}
}
if (balance + 1 <= remaining.left && balance + 1 <= 0) {
result.push(...recurse(current + ')', { left: remaining.left, right: remaining.right - 1 }))
}
}
return result
}
}
function generateParenthesis(n: number): string[] {
return recurse('(', { left: n - 1, right: n })
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment