繁体   English   中英

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

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

我们如何使用Java中的位操作来生成集合的所有可能子集? 例如,如果我们有一个int数组[1, 2, 3] ,则所有可能的子集为:

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

从0到(2 set.size() -1)(包括)进行计数。 检索与当前计数中的1位相对应的元素。 当然,必须对集合进行排序以按索引检索元素。

唯一棘手的部分是提取与当前计数中的1位相对应的元素。 这是一种实现此目的的伪代码:

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

请注意,这假设原始设置的大小不超过您用于计数和掩码的任何整数类型可用的位数。

这是我从网站提取的代码。 还有关于字节表示的进一步说明:

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