Home >Java >javaTutorial >How to Efficiently Generate the Power Set of a Set in Java?
Generating the Powerset of a Set in Java
The powerset of a set is the set of all subsets of that set. For example, the powerset of {1, 2, 3} is:
{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}
Suppose we have a Set in Java:
Set<Integer> mySet = new HashSet<Integer>(); mySet.add(1); mySet.add(2); mySet.add(3); Set<Set<Integer>> powerSet = getPowerset(mySet);
How can we write the getPowerset function with the optimal time complexity?
Solution
The time complexity of the powerset function is O(2^n), where n is the number of elements in the set. This is because the powerset of a set with n elements contains 2^n subsets.
Here's a working implementation of the getPowerset function using generics and sets:
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { Set<Set<T>> sets = new HashSet<Set<T>>(); if (originalSet.isEmpty()) { sets.add(new HashSet<T>()); return sets; } List<T> list = new ArrayList<T>(originalSet); T head = list.get(0); Set<T> rest = new HashSet<T>(list.subList(1, list.size())); for (Set<T> set : powerSet(rest)) { Set<T> newSet = new HashSet<T>(); newSet.add(head); newSet.addAll(set); sets.add(newSet); sets.add(set); } return sets; }
Test
Let's test the getPowerset function with the given example input:
Set<Integer> mySet = new HashSet<Integer>(); mySet.add(1); mySet.add(2); mySet.add(3); for (Set<Integer> s : powerSet(mySet)) { System.out.println(s); }
This will print the following output:
[] [1] [2] [1, 2] [3] [1, 3] [2, 3] [1, 2, 3]
The above is the detailed content of How to Efficiently Generate the Power Set of a Set in Java?. For more information, please follow other related articles on the PHP Chinese website!