Generate Parentheses
Generate Parentheses
BacktrackingRecursion
Problem Statement
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
Example 1:
Input: n = 3
((()))
(()())
(())()
()(())
()()()
Output: ["((()))","(()())","(())()","()(())","()()()"]
Solution
We can solve this problem using backtracking. We build the string of parentheses from left to right. At each step, we have two choices: add a left parenthesis or a right parenthesis. We need to maintain a count of open and closed parentheses to ensure the generated string is well-formed.
Algorithm Steps
- Define a recursive function
backtrack(currentString, openCount, closeCount)
. - If the length of
currentString
is2 * n
, we have a complete combination. Add it to the results and return. - If
openCount < n
, we can add an open parenthesis.- Append
(
tocurrentString
. - Recursively call
backtrack
with updated counts. - Backtrack by removing
(
.
- Append
- If
closeCount < openCount
, we can add a close parenthesis.- Append
)
tocurrentString
. - Recursively call
backtrack
with updated counts. - Backtrack by removing
)
.
- Append
- Initial call:
backtrack("", 0, 0)
.
Generate Parentheses Visualization
n = 3
Progress1 / 1
Ready to start the visualization
Open Brackets
Close Brackets
Current String
0
0
""
Valid Combinations
No solutions found yet...
Generate Parentheses Solution