Medium
Dec 22, 2025#stack
#recursion
22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Example 2:
- 1 <= n <= 8
Constraints:
Notes
- Intuition: Recursively generate by going down the different possible paths to make a well-formed parentheses set. Open and closed must both equal n for it to be well-formed
- Implementation: Recursive function that takes open, closed, n, stack and result. Base case open == close == n, form the string from the stack and add to result. Otherwise, check if open < n, add open to stack, recurse with new count, pop from stack after to go down other path. Check if closed < open (other path), add close to stack, recurse with new count, pop from stack.
- Complexity: Time is complex, something to do with the n-th Catalan number: O(1 / (n + 1) * 2nCn * n), Space O(n) (call stack)