v9.1.1
Menu

Combination Sum

mediumFREEBacktrackingBlind 75

Given an array of distinct integers candidates and a target integer target, return all unique combinations where the chosen numbers sum to target. The same number may be chosen unlimited times. Return a list of combinations, where each combination is a list of integers in ascending order and the combinations are sorted lexicographically. The tests print each combination on its own line with its numbers separated by spaces.

Example

Input
2,3,6,7
7
Output
2 2 3
7
Reasoning
  • Inputs: candidates is the set {2,3,6,7}\{2, 3, 6, 7\} and target is 77. Any candidate may be used any number of times.
  • A combination is a multiset: 2+2+32 + 2 + 3 and 3+2+23 + 2 + 2 are the same answer, written once in ascending order.
  • Checking sums to 7: 7=77 = 7 works on its own. With 66 the remainder is 11, smaller than every candidate, so it fails. Using only 22s gives 2+2+2=62+2+2 = 6 (remainder 11) or 88 (overshoot). Using 33s: 3+3=63 + 3 = 6 leaves 11 again, but one 33 leaves 4=2+24 = 2 + 2, giving 2+2+32 + 2 + 3.
  • No other multiset reaches exactly 77, so there are two answers: {2,2,3}\{2, 2, 3\} and {7}\{7\}.
  • Output: a list of these combinations, each ascending, ordered lexicographically (first elements, then second, ...). Since 2<72 < 7, 2 2 3 comes before 7, even though it is longer.
  • Notice that combinations can differ in length, and the result is empty when no multiset hits the target.

Constraints

  • 1 <= len(candidates) <= 30
  • 2 <= candidates[i] <= 40
  • 1 <= target <= 40

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.