CodingNodes / Backtracking / Combination Sum System design Space play · ←→ step · R restart

Problem

You are given an array candidates of different positive integers and a number target. Return every group of numbers from candidates whose sum is exactly target.

The same number may be used any number of times. Two groups are the same if they use each number the same number of times, so [2,3] and [3,2] count once. The groups may be returned in any order.

Constraints

  • 1 ≤ candidates.length ≤ 30
  • 2 ≤ candidates[i] ≤ 40
  • All numbers in candidates are different
  • 1 ≤ target ≤ 40

Examples: pick one to animate

Solutions

TimeO(n^(t/m)) SpaceO(t/m)

Time: With n candidates, smallest value m and target t, a path is at most t/m numbers long and each level can branch into up to n choices, so the search tree has O(n^(t/m)) nodes.

Space: Besides the output, the path and the recursion are at most t/m deep, because every number added is at least m.

Keep a path and the amount remaining. At each call try every candidate from start onward that still fits. Recurse with the same index so the number can repeat, then undo. Starting at i, never earlier, stops the same group appearing in a different order. When remaining is 0, save a copy of the path.