InterviewPrepKit

Home / Coding / Backtracking

Combination Sum

medium Original β†—
Solving tips
  • This is backtracking where the same element may be reused: recurse with start index i (not i+1) after picking candidates[i] so reuse is allowed.
  • Enforce a canonical non-decreasing order via the start index so each combination is generated exactly once, avoiding the need to dedup [2,3] vs [3,2].
  • Sort candidates first so you can break (not continue) the loop the moment one candidate overshoots the remaining target.
  • Complexity is roughly O(n^(target/min)) time with O(target/min) recursion depth; remember to append path.copy(), not path, at a hit.

Problem

You are given an array candidates of distinct positive integers and a positive integer target. Return every unique combination of candidates whose values sum to exactly target. The same candidate may be used any number of times within one combination. Two combinations are considered the same if they use the same values with the same multiplicities, regardless of order β€” so your answer must not contain duplicates like [2,3] and [3,2]. Combinations may be returned in any order.

Examples

  • candidates = [2,3,6,7], target = 7 β†’ [[2,2,3],[7]] β€” 2+2+3 = 7 (reusing 2 twice) and 7 alone both work.
  • candidates = [2,3,5], target = 8 β†’ [[2,2,2,2],[2,3,3],[3,5]] β€” three distinct multisets reach 8.
  • candidates = [2], target = 1 β†’ [] β€” every candidate exceeds the target, so no combination exists.

Constraints

  • 1 <= len(candidates) <= 30
  • 2 <= candidates[i] <= 40, all values distinct
  • 1 <= target <= 40
  • The number of unique combinations is guaranteed to be fewer than 150.

The small target and the β€œfewer than 150 answers” guarantee tell you an exponential search is expected β€” the game is pruning it so you never build the same combination twice.

Think about it first

Hint 1 Every candidate is at least 2, so a combination can contain at most target/2 numbers. Think of building a combination one number at a time, subtracting from the remaining target as you go.
Hint 2 How do you avoid generating both [2,3] and [3,2]? Force combinations to be built in non-decreasing candidate order: once you move past a candidate, never pick it again in that branch.
Hint 3 Recurse with (start index, remaining). At index i you may pick candidates[i] again (stay at i, since reuse is allowed) or skip ahead. When remaining hits 0, record a copy of the current path; when it goes negative, backtrack. Sorting first lets you cut a whole branch as soon as one candidate overshoots.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.