Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find combination sum solutions

Find all unique combinations of candidates that sum to a target, allowing repeated use of candidates.

Python practice17 minRecursion & BacktrackingIntermediateLast updated March 27, 2026

Problem statement

Given an array of distinct positive 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 use the same candidate number unlimited times. The solution set should not contain duplicate combinations. Return combinations in the order generated by sorted candidates and typical backtracking (build combinations in non-decreasing order).

Task

Use backtracking to explore combinations (reuse allowed), avoid duplicates by sorting candidates and controlling recursion start index.

Examples

Example - candidates = [2,3,6,7], target = 7

Input

[2,3,6,7], 7

Output

[[2, 2, 3], [7]]

2+2+3 and 7 are the valid combinations.

Input format

Two arguments: a list of distinct positive integers candidates, and an integer target.

Output format

A list of lists where each inner list is a combination summing to target. Combinations should be lists of integers in non-decreasing order.

Constraints

1 <= len(candidates) <= 20, candidates[i] > 0, target >= 0. Candidates are distinct. Solutions should be generated deterministically by sorting candidates and using backtracking.

Samples

Sample 1

Input

[2,3,5], 8

Output

[[2, 2, 2, 2], [2, 3, 3], [3, 5]]

All unique combinations that sum to 8.