Using bit subset generated

  definition:

    For any set B, as long as A is included in B then A B is a subset i.e., the number of each set is a subset of 2 ^ n (n is the number of elements in the set)

Regardless of the number 2 ^ n, which is an n-th bit (the first bit is bit 0). It contains a total of 2 ^ n digits.

n = 0 2 ^ n = 1 empty set

n = + 1 is only one collection element 2 ^ 1 2 = empty set

Assume the following n = 2

n=2 There are four elements
Number of elements in the collection Bit representation
0 0
1

01 and 10

2 11

Thus there is, we need to enumerate the 2 ^ n times, each time to check whether the number of digits generated is 1, if there is one, the description should take the corresponding element. code show as below.

void subset(int n,int * a)
{
    for (int i = 0;i < (1 << n);i++)
    {
        for (int j=0;j < i; j++) 
        {
            if (i&(1<<j)) 
            {
                std::cout << a[j]<<" ";
            }
        }
        std::cout << std::endl;


    }

}

 

ON. Posted 2019-06-18 23:51 Well, Cai Cai is read ( ... ) Comments ( ... ) edit collections

Reproduced in: https: //www.cnblogs.com/shuiyonglewodezzzzz/p/11048690.html

Guess you like

Origin blog.csdn.net/weixin_34023863/article/details/93245658