Java:如何实现子集的子集?

时间:2016-11-20 10:24:09

标签: java algorithm set subset

实施后会找到一组的子集,但是有人可以解释if((i&(1<<j)) > 0)正在做什么以及出于什么原因?

评论似乎没有帮助并尝试控制台日志记录,但仍然很难看到它正在做什么。

//Print all subsets of given set[]
static void printSubsets(char set[]) {
    int n = set.length;

    //Run a loop for printing all 2^n subsets one by one
    for(int i=0; i<(1<<n); i++) {
        System.out.print("{ ");

        //Print current subset 
        for(int j=0; j<n; j++) {

            //(1<<j) is a number with jth bit 1
            //so when we 'and' them with the 
            //subset number we get which numbers
            //are present in the subset and which are not
            if((i&(1<<j)) > 0) {
                System.out.print(set[j] + " ");
            }
        }
            System.out.println("}");
    }
}

public static void main(String args[]) {
    char set[] = {'a', 'b', 'c'};
    printSubsets(set);
}

1 个答案:

答案 0 :(得分:1)

在子集中,每个元素可以存在,也可以不存在。因此每个元素只有两种可能的状态:in或out。如果我们查看从0到ProducerThread的数字的二进制表示,其中2^n -1是元素的数量,例如当n时,我们有:

n=3

有8个可能的子集,这些位表示元素是否在子集中。 这是该计划使用的想法:

  • 外部循环从 cba 0 = 000 1 = 001 2 = 010 3 = 011 4 = 100 5 = 101 6 = 110 7 = 111 0
  • 内部循环从2^n-10
  • n-1向左移动1<<j次。

例如,j时,对应于位i=3。 我们从011循环到0,将2i001010进行比较。 对于这些值,表达式100将被评估为 分别为i & (1 << j)011 & 001 = 001011 & 010 = 010。 前两个大于0,最后一个不大于0。 因此011 & 100 = 000将打印System.out.print(set[j] + " ")a