Algorithmssubset sum generation

Subset Sum Generation

TT
Testlaa Team
May 14, 20261 min read

Generate sums by iterating masks and accumulating chosen weights—brute force for small n before optimizing.

Try this in Python

weights = [2, 3, 5]
sums = set()
for mask in range(1 << len(weights)):
    s = 0
    for i in range(len(weights)):
        if (mask >> i) & 1:
            s += weights[i]
    sums.add(s)
print(sorted(sums))

Key takeaways

  • Set avoids duplicate sums when weights repeat conceptually—list may need dedupe.
  • Meet-in-the-middle upgrades this when n grows.
  • Sort sums for two-pointer follow-ups.

Tags:

Bits & subset DPPythonStudents