Problem
Givenn pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Examples
Constraints
- 1 <= n <= 8
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 22 with 11 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 22 # by problem number
lcpy gen -s generate_parentheses # by problem name
n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
class Solution:
# Time: O(4^n / sqrt(n))
# Space: O(4^n / sqrt(n))
def generate_parenthesis(self, n: int) -> list[str]:
result: list[str] = []
def backtrack(s: str, open_count: int, close_count: int) -> None:
if len(s) == 2 * n:
result.append(s)
return
if open_count < n:
backtrack(s + "(", open_count + 1, close_count)
if close_count < open_count:
backtrack(s + ")", open_count, close_count + 1)
backtrack("", 0, 0)
return result
| Time | Space |
|---|---|
| O(4^n / sqrt(n)) | O(4^n / sqrt(n)) |