获得数组的功率集的最好方法



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

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]]

最新更新