找到{1,2,3}的powerset的算法

时间:2011-08-30 17:13:44

标签: java algorithm set hashset

我认为我发现这有点令人困惑,因为我从未真正使用过Java集。有人可以尝试向我展示(最好通过解释如何逐步创建powerset)在下面的代码中(ps我从stackoverflow上的帖子中获取此代码,因此可以归功于该人):

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

1 个答案:

答案 0 :(得分:1)

考虑{1,2,3}的powerset。我们可以将其视为以下组合:

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

{1} + powerset {2, 3}行,扩展为:

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

反过来变成:

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

代码也是如此,使用递归生成较小的powersets并在列表中累积每个集合。