Skip to content

Instantly share code, notes, and snippets.

@manderly
Created August 23, 2021 15:29
Show Gist options
  • Save manderly/28341bd1f5300e18dc43f4c1fe379322 to your computer and use it in GitHub Desktop.
Save manderly/28341bd1f5300e18dc43f4c1fe379322 to your computer and use it in GitHub Desktop.
Leetcode 22: Generate Parentheses
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