简体   繁体   English

使用Java中的位操作的集合的所有可能子集

[英]All possible subsets of a set using bit manipulations in Java

How can we generate all possible subsets of a set using bit manipulations in Java? 我们如何使用Java中的位操作来生成集合的所有可能子集? For example, if we have an int array [1, 2, 3] , all possible subsets are: 例如,如果我们有一个int数组[1, 2, 3] ,则所有可能的子集为:

[            
  [3],       
  [1],       
  [2],       
  [1,2,3],   
  [1,3],     
  [2,3],     
  [1,2],     
  []         
]

Count from 0 to (2 set.size() - 1) (inclusive). 从0到(2 set.size() -1)(包括)进行计数。 Retrieve the elements corresponding to 1 bits in the current count. 检索与当前计数中的1位相对应的元素。 The set will have to be ordered to retrieve elements by index, of course. 当然,必须对集合进行排序以按索引检索元素。

The only tricky part is pulling out the elements corresponding to the 1 bits in the current count. 唯一棘手的部分是提取与当前计数中的1位相对应的元素。 Here's pseudocode for one way to do that: 这是一种实现此目的的伪代码:

for (int pos = 0, mask = 1; mask <= currentCount; mask <<= 1; ++pos) {
    if ((currentCount & mask) != 0) {
        include element at pos in the current subset
    }
}

Note that this assumes that the original set size is no more than the number of bits available for whatever integer type you are using for the count and mask. 请注意,这假设原始设置的大小不超过您用于计数和掩码的任何整数类型可用的位数。

Here is the code I pulled from this website. 这是我从网站提取的代码。 There is further explanation about byte representation there also: 还有关于字节表示的进一步说明:

private static void findSubsets(int array[]) {
    int numOfSubsets = 1 << array.length;

    for (int i = 0; i < numOfSubsets; i++) {
        int pos = array.length - 1;
        int bitmask = i;

        System.out.print("{");
        while (bitmask > 0) {
            if ((bitmask & 1) == 1)
                System.out.print(array[pos] + ",");
            bitmask >>= 1;
            pos--;
        }
        System.out.print("}");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM