> ## 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.

# Combinations Python Solution with Tests

> Tested Python solution for LeetCode 77 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 77, Medium. Topics: Backtracking. [View on LeetCode](https://leetcode.com/problems/combinations/description/).

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

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

## Problem

Given two integers `n` and `k`, return *all possible combinations of* `k` *numbers chosen from the range* `[1, n]`.

You may return the answer in **any order**.

### Examples

```
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
```

**Explanation:** There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., `[1,2]` and `[2,1]` are considered to be the same combination.

```
Input: n = 1, k = 1
Output: [[1]]
```

**Explanation:** There is 1 choose 1 = 1 total combination.

### Constraints

* 1 \<= n \<= 20
* 1 \<= k \<= n

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(C(n,k) * k)
    # Space: O(C(n,k) * k)
    def combine(self, n: int, k: int) -> list[list[int]]:
        result: list[list[int]] = []
        current: list[int] = []

        def backtrack(start: int) -> None:
            if len(current) == k:
                result.append(current[:])
                return

            # Prune: stop early if not enough remaining numbers to reach k
            for num in range(start, n - (k - len(current)) + 2):
                current.append(num)
                backtrack(num + 1)
                current.pop()

        backtrack(1)
        return result
```

## Complexity

| Time           | Space          |
| -------------- | -------------- |
| O(C(n,k) \* k) | O(C(n,k) \* k) |

## Tags

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