Skip to content

Commit

Permalink
Created 22-Generate-Parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
loczek committed Jul 8, 2022
1 parent 04b7acc commit 134207b
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions typescript/22-Generate-Parentheses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
function generateParenthesis(n: number): string[] {
const stack: string[] = [];
const res: string[] = [];

function backtrack(openN: number, closedN: number) {
if (openN === n && closedN === n) {
res.push(stack.join(""));
return;
}

if (openN < n) {
stack.push("(");
backtrack(openN + 1, closedN);
stack.pop();
}

if (closedN < openN) {
stack.push(")");
backtrack(openN, closedN + 1);
stack.pop();
}
}

backtrack(0, 0);

return res;
}

0 comments on commit 134207b

Please sign in to comment.