Essentially, you can break the problem down into: "For each item, will it be part of the set or not". If you can find all combinations of that then you can find all possible ways of selecting items.
A way of representing whether an item is in the set or not is with a Boolean. True or 1 if it is in the set and false or 0 if it isn't. So we need a Boolean for each of the items. This brings to mind an int
or another type as they are all essentially, a bunch of bits.
Now how can we find all combinations of those booleans. There is a simple answer: loop through all the integers. For example:
ABCD Number in base 10
0000 0
0001 1
0010 2
0011 3
0100 4
.... ...
1111 (2^4) - 1
We know there are 2^4
answer since each item can be in the set or not in the set so there are 2 possibilities for each item. If there are 4 element then there are 2*2*2*2
or 2^4
combinations.
There's also an easy way to find 2^n
. Simply doing 1 << n
.
This leads us to the simple answer:
for (int i = 0; i < (1 << n); i++) {
// Here the ath bit of i will be set if the ath item is part of the set
}
Note that this will include the empty set, ie [ ]
. If you don't want this, simply start the loop from 1 instead of 0.
Hope this helps.