【问题标题】:Best way to get a power set of an array? [duplicate]获得阵列功率集的最佳方法? [复制]
【发布时间】:2016-10-23 17:41:14
【问题描述】:

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

int[] A = {1, 2}

并得到以下输出

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

【问题讨论】:

  • 番石榴powerSet()?
  • 我不认为这是重复的。对于某些用例,我们可能不想将数组转换为 Set。此问题的建议解决方案比设置解决方案更快。

标签: java arrays powerset


【解决方案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]]

【讨论】:

  • 非常感谢。
猜你喜欢
  • 2017-12-17
  • 2015-10-02
  • 1970-01-01
  • 2016-03-27
  • 2010-09-16
  • 2016-06-22
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多