MediumNo. 0022
Generate Parentheses — LeetCode 22 Python Solution
- Pattern
- Backtracking
- Topics
- String, Dynamic Programming, Backtracking
- On study lists
- NeetCode 150 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0131 | Palindrome Partitioning | Medium |
| 2002 | Maximum Product of the Length of Two Palindromic Subsequences | Medium |
| 0032 | Longest Valid Parentheses | Hard |
| 0010 | Regular Expression Matching | Hard |
| 0044 | Wildcard Matching | Hard |
| 0072 | Edit Distance | Medium |
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.