获得阵列电源的最佳方法是什么?例如,如果我有一个数组:
int[] A = {1, 2}
并获得以下输出
int[] P = {{}, {1}, {2}, {1, 2}}
答案 0 :(得分:1)
试试这个。
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]]