I\'m working through an interview question that goes like:
Given an array of integers and sum, check whether any combination adds up to the sum.>
One handy insight is to realize that the binary representation of all numbers from 0
to (2^N)-1
is actually a set of bit masks for the possible combinations out of N
distinct items. For instance, for N=3
(3 items) and thus (2^3)-1 = 7
:
0: 000 = none
1: 001 = third item
2: 010 = second item
3: 011 = second and third items
4: 100 = first item
5: 101 = first and third items
6: 110 = first and second items
7: 111 = all 3 items
This makes it very easy to loop through all possible selections in a set order (so that it's impossible to skip or double-visit any potential selection).