Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times.

Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times.
def combos(c, t):
    c.sort(); res = 0
    def go(start, rem):
        nonlocal res
        if rem == 0: res += 1; return
        for i in range(start, len(c)):
            if c[i] > rem: break
            go(i, rem - c[i])
    go(0, t)
    return res
print(combos([3, 4, 5, 7], 15))
What is printed?
  1. A. 4
  2. B. 9
  3. C. 7
  4. D. 6

Correct answer: D. 6

Passing i (not i + 1) allows reuse, and never going back below start avoids counting 3+5+7 and 7+5+3 separately. The combinations are 3+5+7, 4+4+7, 5+5+5, 3+3+4+5, 3+4+4+4 and 3+3+3+3+3: 6 in all.

More Coding Interview Problems questions

Exams that ask this topic