All possible subsets of a set using bit manipulations in Java -
how can generate possible subsets of set using bit manipulations in java? example, if have int array [1, 2, 3]
, possible subsets are:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
count 0 (2set.size()
- 1) (inclusive). retrieve elements corresponding 1 bits in current count. set have ordered retrieve elements index, of course.
the tricky part pulling out elements corresponding 1 bits in current count. here's pseudocode 1 way that:
for (int pos = 0, mask = 1; mask <= currentcount; mask <<= 1; ++pos) { if ((currentcount & mask) != 0) { include element @ pos in current subset } }
note assumes original set size no more number of bits available whatever integer type using count , mask.
Comments
Post a Comment