Generate Parentheses Visualizer & Step-by-Step Algorithm Solution

Generate all combinations of well-formed parentheses using recursive backtracking with open and close count pruning.

Category: backtracking | Difficulty: Medium

Tags: Backtracking, Recursion, String, Decision Tree, LeetCode 22

Generate Parentheses

""
Result Combinations
100%
state
n2
totalPairs2
targetLength4
totalValid0
Start
1/40
Explanation

Start generateParenthesis(n = 2). We need to generate all combinations of well-formed parentheses containing 2 pairs (4 characters total).

Source Code
1function generateParenthesis(n: number): string[] {
2 const result: string[] = [];
3 function backtrack(curr: string, open: number, close: number) {
4 if (curr.length === n * 2) {
5 result.push(curr);
6 return;
7 }
8 if (open < n) backtrack(curr + "(", open + 1, close);
9 if (close < open) backtrack(curr + ")", open, close + 1);
10 }
11 backtrack("", 0, 0);
12 return result;
13}