SDE & MLE Prep

22. Generate Parentheses

Problem

Return every well-formed string of n pairs of parentheses.

Example: n = 3 → ["((()))","(()())","(())()","()(())","()()()"]

Constraints: n ≤ 8.

Add ( while open < n; add ) while close < open. These two rules generate exactly the valid strings.

              ""
          "("
       "(("      "()"
   "(()"  ...    "()("
  "(())"         "()()"

Complexity: O(Catalan(n) · n) ≈ O(4ⁿ/√n).

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        res = []

        def bt(cur, op, cl):
            if len(cur) == 2 * n:
                res.append(cur)
                return
            if op < n:
                bt(cur + "(", op + 1, cl)
            if cl < op:
                bt(cur + ")", op, cl + 1)

        bt("", 0, 0)
        return res