以递归方式打印数组的所有子集

时间:2016-05-03 14:40:02

标签: java

我想在main方法中递归地打印生成的数组的所有子集。

以下行显示我的代码。我不知道如何递归地实现方法subsets()。

public class Main {

    // Make random array with length n
    public static int[] example(int n) {
        Random rand = new Random();
        int[] example = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            example[i] = rand.nextInt(100);
        }
        Arrays.sort(example, 1, n + 1);
        return example;
    }

    // Copy content of a boolean[] array into another boolean[] array
    public static boolean[] copy(boolean[] elements, int n) {
        boolean[] copyof = new boolean[n + 1];
        for (int i = 1; i <= n; i++) {
            copyof[i] = elements[i];
        }

        return copyof;
    }

    // Counts all subsets from 'set'
    public static void subsets(int[] set, boolean[] includes, int k, int n) {

       // recursive algo needed here!

    }

    public static void main(String[] args) {
        // index starts with 1, -1 is just a placeholder.
        int[] setA = {-1, 1, 2, 3, 4};
        boolean[] includesA = new boolean[5];
        subsets(setA, includesA, 1, 4);

    }

}

2 个答案:

答案 0 :(得分:0)

如果是使用第三方库的选项,Guava Sets类可以为您提供所有可能的子集。查看the powersets method

答案 1 :(得分:0)

这是一种非递归技术:

public List<Set<Integer>> getSubsets(Set<Integer> set) {
    List<Set<Integer>> subsets = new ArrayList<>();

    int numSubsets = 1 << set.size(); // 2 to the power of the initial set size

    for (int i = 0; i < numSubsets; i++) {
        Set<Integer> subset = new HashSet<>();
        for (int j = 0; j < set.size(); j++) {
            //If the jth bit in i is 1
            if ((i & (1 << j)) == 1) {
                subset.add(set.get(i));
            }
        }
        subsets.add(subset);
    }
    return subsets;
}

如果您只想要唯一(通常是无序)子集,请使用Set<Set<Integer>>代替List<Set<Integer>>