> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Generate Parentheses Python Solution

> Tested Python solution for LeetCode 22 with 11 pytest cases. Generate a practice environment with lcpy.

LeetCode 22, Medium. Topics: String, Dynamic Programming, Backtracking. [View on LeetCode](https://leetcode.com/problems/generate-parentheses/description/).

Generate this problem as a practice environment: tested reference solution, 11 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 22   # by problem number
lcpy gen -s generate_parentheses   # by problem name
```

## Problem

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

### Examples

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

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

### Constraints

* 1 \<= n \<= 8

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/generate_parentheses/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/generate_parentheses/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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
```

## Complexity

| Time             | Space            |
| ---------------- | ---------------- |
| O(4^n / sqrt(n)) | O(4^n / sqrt(n)) |

## Tags

[Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
