CodeArchon

mediumBacktrackingAmazonFacebookSnapchat

Coin Combo Mint

A vending mint lists every multiset of coin denominations whose face values sum to a target amount.

Given distinct positive integers and a target, return all unique combinations that sum to the target. Each denomination may be chosen unlimited times.

Choose approach

2
0
j
3
1
6
2
7
3
SetCombos (0)
empty
1/19
Narrationstep 1 of 19

DFS from index 0 with target 7.

1def combinationSum(cands, target):
2 out, cur = [], []
3 cands.sort()
4 def dfs(i, remain):
5 if remain == 0:
6 out.append(cur[:]); return
7 for j in range(i, len(cands)):
8 if cands[j] > remain: break
9 cur.append(cands[j]); dfs(j, remain - cands[j]); cur.pop()
10 dfs(0, target); return out
Variables
remain=7
cur=[]
outCount=0

How to think about it

  1. Sorting enables the `cands[j] > remain` prune.
  2. Reusing index `j` instead of `j+1` allows unlimited picks of the same denomination.
  3. Hitting remain=0 emits a combo; negative remain is pruned by the break.

Edge cases to catch in interview

  • Target 0 -> single empty combo.
  • No candidate ≤ target -> empty.

Examples

Example 1[[2,2,3],[7]]
{"values":[2,3,6,7],"target":7}
Example 2[[2,2,2,2],[2,3,3],[3,5]]
{"values":[2,3,5],"target":8}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed