获得数组幂集的最佳方法?

Best way to get a power set of an array?

获得数组幂集的最佳方法是什么?例如,如果我有一个数组:

int[] A = {1, 2}

并得到如下输出

int[] P = {{}, {1}, {2}, {1, 2}}

试试这个。

int[] a = {1, 2};
int max = 1 << a.length;
int[][] result = new int[max][];
for (int i = 0; i < max; ++i) {
    result[i] = new int[Integer.bitCount(i)];
    for (int j = 0, b = i, k = 0; j < a.length; ++j, b >>= 1)
        if ((b & 1) != 0)
            result[i][k++] = a[j];
}
System.out.println(Arrays.deepToString(result));

结果:

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