Data Structures & AlgorithmsHardICPC regional · bitmask round

Problem: How many subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum of exactly 10?

Problem: How many subsets of {1, 2, 3, 4, 5, 6, 7, 8} have a sum of exactly 10?
cnt = 0
for m in range(1 << 8):
    if sum(i + 1 for i in range(8) if m >> i & 1) == 10:
        cnt += 1
print(cnt)
What is printed?
  1. A. 6
  2. B. 10
  3. C. 12
  4. D. 8

Correct answer: D. 8

The subsets are {2,8}, {3,7}, {4,6}, {1,2,7}, {1,3,6}, {1,4,5}, {2,3,5} and {1,2,3,4}. The empty set and sets with any element above 8 are not counted.

More Coding Interview Problems questions

Exams that ask this topic