Skip to content
CodeShare
All problems

Combination Sum

Find every combination that adds up to a target, reusing numbers freely.

MediumBacktracking

Given an array of distinct positive integers candidates and a target, return every unique combination of candidates that adds up to target. The same number may be used any number of times.

Two combinations are the same if they use each number the same number of times. You can return the combinations in any order, and the numbers inside each combination in any order.

Examples

Example 1
Input
candidates = [2, 3, 6, 7], target = 7
Output
[[2, 2, 3], [7]]
Example 2
Input
candidates = [2, 3, 5], target = 8
Output
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Example 3
Input
candidates = [2], target = 1
Output
[]

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All candidates are distinct.
  • 1 <= target <= 40