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

# Combination Sum Python Solution with Tests

> Tested Python solution for LeetCode 39 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 39, Medium. Topics: Array, Backtracking. [View on LeetCode](https://leetcode.com/problems/combination-sum/description/).

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

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

## Problem

Given an array of **distinct** integers `candidates` and a target integer `target`, return *a list of all **unique combinations** of* `candidates` *where the chosen numbers sum to* `target`. You may return the combinations in **any order**.

The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.

### Examples

```
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
```

**Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations.

```
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
```

```
Input: candidates = [2], target = 1
Output: []
```

### Constraints

* 1 \<= candidates.length \<= 30
* 2 \<= candidates\[i] \<= 40
* All elements of candidates are distinct.
* 1 \<= target \<= 40

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(N^(T/M)) where N=len(candidates), T=target, M=min(candidates)
    # Space: O(T/M) recursion + O(K * T/M) output, where K = number of solutions
    def combination_sum(self, candidates: list[int], target: int) -> list[list[int]]:
        result = []

        def backtrack(start: int, path: list[int], remaining: int) -> None:
            if remaining == 0:
                result.append(path[:])
                return

            for i in range(start, len(candidates)):
                if candidates[i] <= remaining:
                    path.append(candidates[i])
                    backtrack(i, path, remaining - candidates[i])
                    path.pop()

        backtrack(0, [], target)
        return result
```

## Complexity

| Time                                                            | Space                                                                |
| --------------------------------------------------------------- | -------------------------------------------------------------------- |
| O(N^(T/M)) where N=len(candidates), T=target, M=min(candidates) | O(T/M) recursion + O(K \* T/M) output, where K = number of solutions |

## Tags

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