22. Generate Parentheses

Updated: 2024-03-12
1 min read

LeetCode problem

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

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

Example 2:

Input: n = 1
Output: ["()"]

Prerequirements

Backtracking pattern

First accepted

Idea:

test-case

class Solution:
  def generateParenthesis(self, n):
    res = []

    def dfs(l: int, r: int, s: str) -> None:
      if l == 0 and r == 0:
        res.append(s)
      if l > 0:
        dfs(l - 1, r, s + '(')
      if l < r:
        dfs(l, r - 1, s + ')')

    dfs(n, n, '')
    return res