Generate Parentheses
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Solution
Use backtracking to generate all possible combinations of parentheses. Start with an empty string and add a (
if the number of open parentheses is less than n
and add a )
if the number of close parentheses is less than the number of open parentheses. If the length of the current string is equal to n * 2
, add the current string to the result.
Implementation
Pseudocode
Main function
- Create a variable
max
and set it ton * 2
- Create an empty array
result
- Create a function
backtrack
that takescurrent
,open
,close
as arguments - Call the
backtrack
function with an empty string""
,0
, and0
Backtracking function
-
Check if the length of the current string is equal to
max
. If it is, add the current string to the result and return -
If the number of open parentheses is less than
n
, call the backtrack function with the current string concatenated with an open parentheses(
,open + 1
, andclose
-
If the number of close parentheses is less than the number of open parentheses, call the backtrack function with the current string concatenated with a close parentheses
)
,open
, andclose + 1
Complexity Analysis
-
The time complexity of this algorithm is
O(4^n / sqrt(n))
because for each of the2n
positions, we can either put an open or close parentheses, giving us2^2n
possibilities. However, not all these possibilities are valid. We use the Catalan number to estimate the number of valid combinations, which isO(4^n / sqrt(n))
-
The space complexity of this algorithm is
O(4^n / sqrt(n))
because we are using recursion and the maximum depth of the recursion tree is2n