Data Structures & AlgorithmsHardProduct company OA

Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing order).

Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing order).
def comb_sum(cands, target):
    res = []
    def bt(i, rem, path):
        if rem == 0: res.append(path[:]); return
        for j in range(i, len(cands)):
            if cands[j] > rem: break
            path.append(cands[j]); bt(j, rem - cands[j], path); path.pop()
    bt(0, target, [])
    return res
r = comb_sum([3, 4, 5], 15)
print(len(r), r[1])
What is printed?
  1. A. 3 [3, 3, 4, 5]
  2. B. 4 [3, 4, 4, 4]
  3. C. 4 [3, 3, 4, 5]
  4. D. 6 [3, 3, 4, 5]

Correct answer: C. 4 [3, 3, 4, 5]

Recursing with bt(j, …) (not j + 1) allows reuse, and never going back to smaller indices avoids permutations of the same multiset. Combinations: 3×5, 3+3+4+5, 3+4+4+4, 5×3 → 4. Counting ordered sequences would give many more. The 'break' prunes because the candidates are sorted.

More Coding Interview Problems questions

Exams that ask this topic