Skip to content
BytePatterns

Combinations That Sum

MediumBacktracking#backtracking#pruning~25m

Problem

Given a list of distinct positive numbers and a target, return every group of them that adds up exactly to the target. A number may be used as many times as you like, and two groups holding the same numbers in a different order count as one answer.

Examples

Input:  nums = [2, 3, 6, 7], target = 7
Output: [[2, 2, 3], [7]]
Why:    2 + 2 + 3 and 7 on its own; 3 + 2 + 2 is the same group
Input:  nums = [2], target = 4
Output: [[2, 2]]
Why:    the same number may be reused
Input:  nums = [3, 5], target = 4
Output: []
Why:    edge case, no combination of 3 and 5 lands on 4

Hints

0 / 3

Stuck on the idea rather than the code? Subsets covers it.