开发者

Algorithm to find powerset of {1,2,3}

I think i'm finding this a little confusing because i've never really used Java sets. Could someone please try and show me (preferably by explaining how the powerset is gradually being created) in the following code (ps i got this code from a post on stackoverflow, so credit goes to that person):

public static void main(String[] args) {
        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);
        }开发者_如何学运维

    }

    public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
        Set<Set<T>> sets = new HashSet<Set<T>>();

        //If the input is empty, add the empty set and return
        if (originalSet.isEmpty()) {
            sets.add(new HashSet<T>());
            return sets;
        }

        //Put the originalSet into an arraylist
        List<T> list = new ArrayList<T>(originalSet);

        //Get the first element
        T head = list.get(0);

        //Get everything but the first element and put into a set
        Set<T> rest = new HashSet<T>(list.subList(1, list.size()));

        //For each element in the set above
        for (Set<T> set : powerSet(rest)) {

            //Create a new set
            Set<T> newSet = new HashSet<T>();

            //Add the head
            newSet.add(head);

            //Add the rest
            newSet.addAll(set);

            //Add all of newset to the result
            sets.add(newSet);

            //Add the current element
            sets.add(set);
        }
        return sets;
    }


Think about the powerset of {1, 2, 3}. We can think of it as a combination of:

{}  
{1} + powerset {2, 3}  
{2} + powerset {3}  
{3} + powerset {}

Taking the line {1} + powerset {2, 3}, this expands to:

{1} + { {}, {2}, {3}, {2, 3} }

which in turn becomes:

{ {1}, {1, 2}, {1, 3}, {1, 2, 3} }

The code is doing the same, using recursion to generate the smaller powersets and accumulating each set in a list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜