Home > Java > javaTutorial > How to Efficiently Generate the Power Set of a Set in Java?

How to Efficiently Generate the Power Set of a Set in Java?

Linda Hamilton
Release: 2024-12-14 22:41:14
Original
252 people have browsed it

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);
Copy after login

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;
}  
Copy after login

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);
}
Copy after login

This will print the following output:

[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template