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.
What programming technique does one use when they want to try all possible combinations of a set?
Even if that isn't the best solution to this problem, I come across problems where I need to either generate or do something with all combinations of a list, and I'd like to know how to handle that.
One handy insight is to realize that the binary representation of all numbers from
(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).