MediumNo. 0022

Generate Parentheses — LeetCode 22 Python Solution

Topics
String, Dynamic Programming, Backtracking
Reading time
2 min

The problem

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

Example

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

Python solution

PythonSolution
class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        def dfs(l, r, t):
            if l > n or r > n or l < r:
                return
            if l == n and r == n:
                ans.append(t)
                return
            dfs(l + 1, r, t + '(')
            dfs(l, r + 1, t + ')')

        ans = []
        dfs(0, 0, '')
        return ans

Complexity

Time
O(2n × 2 × n)
Space · auxiliary
O(n)

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 22. Generate Parentheses is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 22. Generate Parentheses?

LeetCode 22. Generate Parentheses is rated Medium on LeetCode.

What is the time complexity of LeetCode 22. Generate Parentheses?

The Python solution on this page runs in O(2n × 2 × n).

What is the space complexity of LeetCode 22. Generate Parentheses?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 22. Generate Parentheses cover?

LeetCode 22. Generate Parentheses is tagged String, Dynamic Programming and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.