Given n pairs of parentheses, generate all combinations of well-formed parentheses.
Only build valid prefixes: add '(' while fewer than n are open, and add ')' only when it would close an open one.
1function generateParenthesis(n: number): string[] {2const res: string[] = [], path: string[] = [];3function dfs(open: number, close: number) {4if (path.length === 2 * n) { res.push(path.join("")); return; }5if (open < n) { path.push("("); dfs(open + 1, close); path.pop(); }6if (close < open) { path.push(")"); dfs(open, close + 1); path.pop(); }7}8dfs(0, 0);9return res;10}
open 0 < 3: add '('.
Space: play/pause · ←/→: step