Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once).

Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once).
def combo(k, s, n=9):
    out = []
    def bt(start, cur, rem):
        if len(cur) == k:
            if rem == 0: out.append(cur[:])
            return
        for x in range(start, n + 1):
            if x > rem: break
            cur.append(x); bt(x + 1, cur, rem - x); cur.pop()
    bt(1, [], s)
    return out
print(combo(3, 9))
What is printed?
  1. A. [[1, 2, 6], [1, 3, 5], [2, 3, 4], [3, 3, 3]]
  2. B. [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
  3. C. [[1, 2, 6], [1, 3, 5]]
  4. D. [[1, 3, 5], [2, 3, 4]]

Correct answer: B. [[1, 2, 6], [1, 3, 5], [2, 3, 4]]

Choosing increasing numbers (start = x + 1) prevents reuse and duplicate orderings, and 'break' prunes once x exceeds the remainder. Sets of 3 distinct digits summing to 9: {1,2,6}, {1,3,5}, {2,3,4}. [3,3,3] repeats a number.

More Coding Interview Problems questions

Exams that ask this topic