Combination Sum
1 approach, code in every language
Problem description
You are given a list of distinct positive integers called candidates and a positive whole number target. Find every unique group of numbers drawn from candidates whose elements add up exactly to target. A single candidate value may be reused as many times as you like within one group.
Two groups are considered the same if they contain the identical multiset of numbers regardless of order, so each distinct combination should be reported only once. Return all the combinations in any order.
Example 1
Input: candidates = [2, 3, 6, 7], target = 7
Output: [[2, 2, 3], [7]]
Two plus two plus three equals seven, and seven by itself also reaches the target.
Example 2
Input: candidates = [2, 3, 5], target = 8
Output: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Each listed group sums to eight and no group repeats another as a multiset.
Constraints
1 <= candidates.length <= 302 <= candidates[i] <= 40All values in candidates are distinct1 <= target <= 500
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Exact Postage Mixes is our own problem on the technique behind Combination Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free