Created
August 23, 2021 15:29
-
-
Save manderly/28341bd1f5300e18dc43f4c1fe379322 to your computer and use it in GitHub Desktop.
Leetcode 22: Generate Parentheses
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 generateParenthesis(n: number): string[] { | |
if (n === 1) { return ["()"]; } | |
let result = new Set<string>(); | |
let previousCombos = generateParenthesis(n-1); | |
for (let i in previousCombos) { | |
let combo = previousCombos[i]; | |
// wrap all previous entries in parens and put those in the set | |
result.add("("+combo+")"); | |
// now step through each one and embed a new paren at each possible position | |
for (let i = 0; i < combo.length; i++) { | |
result.add(combo.substring(0,i) + '()' + combo.substring(i)); | |
} | |
} | |
return [...result]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment