Algorithmssubset sum generation
Subset Sum Generation
TT
Testlaa Team
May 14, 2026•1 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
ngrows. - Sort sums for two-pointer follow-ups.
Tags:
Bits & subset DPPythonStudents
