Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example:
- Input:
n = 2
- Output:
["(())", "()()"]
Approach: Backtracking
To solve this problem, we use backtracking to explore all possible combinations of parentheses. The idea is to generate strings by adding '('
and ')'
recursively, while ensuring that at any point:
- We do not have more closing parentheses
')'
than opening'('
. - We do not exceed
n
pairs of parentheses.
Generate Parentheses Code in JavaScript:
function generateParentheses(n) {
const result = [];
function backtrack(openCount, closeCount, current) {
if (current.length === n * 2) {
result.push(current);
return;
}
if (openCount < n) {
backtrack(openCount + 1, closeCount, current + '(');
}
if (closeCount < openCount) {
backtrack(openCount, closeCount + 1, current + ')');
}
}
backtrack(0, 0, '');
return result;
}
// Example Usage
console.log(generateParentheses(2)); // Output: ["(())", "()()"]
Explanation of the Code
- Backtracking Function: The
backtrack
function is called recursively to build the combinations. - Parameters:
openCount
: Number of'('
used so far.closeCount
: Number of')'
used so far.current
: Current string being built.
- Base Case: If the length of
current
equalsn * 2
(since each pair has two characters), we have a valid combination. - Recursive Calls:
- Add
'('
if possible: IfopenCount
is less thann
, we can add another'('
. - Add
')'
if valid: IfcloseCount
is less thanopenCount
, we can add a')'
to maintain balance.
- Add
Recursive State Tree (n = 2)
The diagram below represents the recursive state tree for generating parentheses with n = 2
.
Explanation of the Diagram:
- Root Node
A
(“Start: ‘’”): Start with an empty string, withopen
andclose
counts at0
. - Node
B1
(“Add ‘(’: ‘(’ (open=1, close=0)”): Add an opening parenthesis'('
to the string, incrementingopen
to1
. - Node
C1
(“Add ‘(’: ‘((’ (open=2, close=0)”): Add another'('
, incrementingopen
to2
. - Node
D1
(“Add ‘)’: ‘(()’ (open=2, close=1)”): Now we must add a closing parenthesis')'
sinceopen
has reachedn
. - Node
E1
(“Add ‘)’: ‘(())’ (open=2, close=2)”): Add another')'
, reachingn
pairs, and we have a valid combination'(())'
. - Node
C2
(“Add ‘)’: ‘()’ (open=1, close=1)”): Backtrack to a valid state and add')'
. - Node
D2
(“Add ‘(’: ‘()(’ (open=2, close=1)”): Add another'('
, creatingopen=2
. - Node
E2
(“Add ‘)’: ‘()()’ (open=2, close=2)”): Add the last')'
to form another valid combination"()()"
.
Key Points to Remember:
- Recursive Exploration: Explore all possible valid combinations by adding
'('
and')'
. - Backtracking: Use backtracking to undo the last action and explore other possibilities when necessary.
- Valid Parentheses Check: Maintain the condition that at no point can the count of
')'
exceed the count of'('
.
.