← All Exercises

Combination Sum with Backtracking

intermediatepython~25min

Background

Combination sum is the unbounded version of subset search and models coin combinations, menu pricing, and capacity filling.

Problem

Given distinct positive candidates and a target, return all unique combinations whose values sum to the target, reusing candidates as often as needed.

Input

A list of distinct positive integers and a positive target; candidates may be given in any order.

Output

A list of combinations, each sorted ascending, with no duplicate combinations.

Sample tests

Sample 1

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

Sample 2

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

Sample 3

Input: candidates = [2], target = 1
Expected: []

Your solution

Learning objective

Adapt the subset backtracking template to unbounded reuse while avoiding duplicate combinations.