Java – lists all possible subsets

I have a list of elements (1, 2, 3), and I need to get a superset (no duplicate elements) of the list So basically I need to create a list:

{1}
{2}
{3}
{1,2}
{1,3}
{2,3}
{1,3}

What is the best (simple & efficient in this case, the list won't be huge) way to achieve this? It's best in Java, but any language solution will be useful

Solution

Use bitmask:

int allMasks = (1 << N);
for (int i = 1; i < allMasks; i++)
{
    for (int j = 0; j < N; j++)
        if ((i & (1 << j)) > 0) //The j-th element is used
           System.out.print((j + 1) + " ");

    System.out.println();
}

Here are all bitmasks:

1 = 001 = {1}
2 = 010 = {2}
3 = 011 = {1,2}
4 = 100 = {3}
5 = 101 = {1,3}
6 = 110 = {2,3}
7 = 111 = {1,3}

You know in binary that the first is the rightmost

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>