首页 > 解决方案 > 如何将powerSet的内容保存到Java中的二维数组中

问题描述

我正在尝试将从一维数组获得的 PowerSet 的内容保存到二维数组中。我尝试在“if”语句中分配数组中的值,但我得到的索引完全错误

int[] set = new int[]{2,4,5,8}
int powSetLength = (int) Math.pow(2,set.length);
int[][] powSet = new int[powSetLength][];


    for (int i = 0; i<powSetLength; i++){

        for (int j = 0; j<set.length; j++){
            if ((i & (1<<j))>0) {
                powSet[i] = new int[] //here needs to be the length corresponding to the subset
                powSet[i][j] = set[j]; //I know this is wrong but my idea was to assign each number of a subset into the 2d array
            }
        }
    }

标签: javaarrayssubsetpowerset

解决方案


由于您的内部数组是可变长度的,因此您可能希望使用内部数组java.util.ArrayList<Integer>。像这样的东西:

int[] set = new int[]{2,4,5,8};
int powSetLength = (int) Math.pow(2,set.length);
List<Integer>[] powSet = new List[powSetLength];

for (int i = 0; i<powSetLength; i++){
    for (int j = 0; j<set.length; j++){
        if ((i & (1<<j))>0) {
            // If the `i`'th powerSet isn't initialized yet: create an empty ArrayList:
            if(powSet[i] == null)
                powSet[i] = new ArrayList<>();
            // And add the current set-value to the List:
            powSet[i].add(set[j]);
        }
    }
}

System.out.println(Arrays.toString(powSet));

之后,您的列表数组将包含以下 powerset:

[null, [2], [4], [2, 4], [5], [2, 5], [4, 5], [2, 4, 5], [8], [2, 8], [4, 8], [2, 4, 8], [5, 8], [2, 5, 8], [4, 5, 8], [2, 4, 5, 8]]

在线尝试。


推荐阅读