简体   繁体   中英

Print all subsets of an array recursively

I want to print all subsets of the generated arrays recursively in the main method.

The following lines show my Code. I don't know how to implement the method subsets() recursively.

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. Check out the powersets method .

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>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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