位运算:获取集合的子集

设集合的元素个数为m,则集合的子集个数为2^m,可用0—2^m-1表示m的所有子集。

例:集合{3,6,7},元素个数为3,子集个数为8

则正好可以用0—7表示这8个子集

0  0  0:{}

0  0  1:{7}

0  1  0:{6}

0  1  1:{6,7}

1  0  0:{3}

1  0  1:{3,7}

1  1  0:{3,6}

1  1  1:{3,6,7}

代码如下:

public static List<List<Integer>> getSubSets(List<Integer> set){
    List<List<Integer>> result = new LinkedList<>();
    for(int i=0;i<Math.pow(2,set.size());++i){
        List<Integer> subSet = new LinkedList<>();
        for(int j=0,index=i;j<set.size();++j,index>>=1)
            if((index&1)==1)
                subSet.add(set.get(j));
        result.add(subSet);
     }
    return result;
}
原文地址:https://www.cnblogs.com/xiehuazhen/p/10153914.html