用位运算获得集合的所有子集

来源:互联网 发布:视频特效软件 编辑:程序博客网 时间:2024/05/22 02:28

引自 bmerry's  bitmark tutorial in Topcoder:

All the subsets

A big advantage of bit manipulation is that it is trivial to iterate over all the subsets of an N-element set: every N-bit value represents some subset. Even better, if A is a subset of B then the number representing A is less than that representing B, which is convenient for some dynamic programming solutions. It is also possible to iterate over all the subsets of a particular subset (represented by a bit pattern), provided that you don't mind visiting them in reverse order (if this is problematic, put them in a list as they're generated, then walk the list backwards). The trick is similar to that for finding the lowest bit in a number. If we subtract 1 from a subset, then the lowest set element is cleared, and every lower element is set. However, we only want to set those lower elements that are in the superset. So the iteration step is just i = (i - 1) & superset.  

这是我写的实验,三个元素的集合,111表示:

#include<iostream>

using namespace std; int main()

{    int bitNumber = 7;   

while ((bitNumber-1)!=0)

{        bitNumber = (bitNumber-1);       

 printf("%d %d %d/n", bitNumber>>2, (bitNumber&2)>>1, bitNumber&1);    }           return 0;

}