Created
December 8, 2022 12:35
-
-
Save selcukcihan/d0d3612b8d4b644ecc63633cddf52a10 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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