Skip to content

Commit 134207b

Browse files
committed
Created 22-Generate-Parentheses
1 parent 04b7acc commit 134207b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

typescript/22-Generate-Parentheses.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function generateParenthesis(n: number): string[] {
2+
const stack: string[] = [];
3+
const res: string[] = [];
4+
5+
function backtrack(openN: number, closedN: number) {
6+
if (openN === n && closedN === n) {
7+
res.push(stack.join(""));
8+
return;
9+
}
10+
11+
if (openN < n) {
12+
stack.push("(");
13+
backtrack(openN + 1, closedN);
14+
stack.pop();
15+
}
16+
17+
if (closedN < openN) {
18+
stack.push(")");
19+
backtrack(openN, closedN + 1);
20+
stack.pop();
21+
}
22+
}
23+
24+
backtrack(0, 0);
25+
26+
return res;
27+
}

0 commit comments

Comments
 (0)