Logo for ammarahmed.ca
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:

1Input: n = 3 2Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

1Input: n = 1 2Output: ["()"]
  • 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)

          Solution

          1from typing import List 2 3class Solution: 4 def backtrack(self, open: int, closed: int, n: int, stack: List[str], result: List[str]): 5 if open == closed and closed == n: 6 result.append("".join(stack)) 7 return 8 9 if open < n: 10 stack.append("(") 11 self.backtrack(open + 1, closed, n, stack, result) 12 stack.pop() 13 14 if closed < open: 15 stack.append(")") 16 self.backtrack(open, closed + 1, n, stack, result) 17 stack.pop() 18 19 20 def generateParenthesis(self, n: int) -> List[str]: 21 result = [] 22 stack = [] 23 self.backtrack(0, 0, n, stack, result) 24 return result 25 26 27 28 29if __name__ == "__main__": 30 # Include one-off tests here or debugging logic that can be run by running this file 31 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 32 solution = Solution() 33