简体   繁体   English

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

[英]Print all subsets of an array recursively

I want to print all subsets of the generated arrays recursively in the main method. 我想在main方法中递归地打印生成的数组的所有子集。

The following lines show my Code. 以下行显示我的代码。 I don't know how to implement the method subsets() recursively. 我不知道如何递归地实现方法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);

    }

}

If it's an option to use a third party library, the Guava Sets class can give you all the possible subsets. 如果它是使用第三方库的选项,Guava Sets类可以为您提供所有可能的子集。 Check out the powersets method . 查看powersets方法

Here's a non-recursive technique: 这是一种非递归技术:

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;
}

If you want only unique (and usually unordered) subsets, use a Set<Set<Integer>> instead of List<Set<Integer>> . 如果只想要唯一(通常是无序)子集,请使用Set<Set<Integer>>而不是List<Set<Integer>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM