Obtaining a powerset of a set in Java

后端 未结 26 1702
青春惊慌失措
青春惊慌失措 2020-11-22 11:33

The powerset of {1, 2, 3} is:

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

Let\'s say I have a Set in Java:<

相关标签:
26条回答
  • 2020-11-22 12:01

    If S is a finite set with N elements, then the power set of S contains 2^N elements. The time to simply enumerate the elements of the powerset is 2^N, so O(2^N) is a lower bound on the time complexity of (eagerly) constructing the powerset.

    Put simply, any computation that involves creating powersets is not going to scale for large values of N. No clever algorithm will help you ... apart from avoiding the need to create the powersets!

    0 讨论(0)
  • 2020-11-22 12:07

    I was looking for a solution that wasn't as huge as the ones posted here. This targets Java 7, so it will require a handful of pastes for versions 5 and 6.

    Set<Set<Object>> powerSetofNodes(Set<Object> orig) {
        Set<Set<Object>> powerSet = new HashSet<>(),
            runSet = new HashSet<>(),
            thisSet = new HashSet<>();
    
        while (powerSet.size() < (Math.pow(2, orig.size())-1)) {
            if (powerSet.isEmpty()) {
                for (Object o : orig) {
                    Set<Object> s = new TreeSet<>();
                    s.add(o);
                    runSet.add(s);
                    powerSet.add(s);
                }
                continue;
            }
            for (Object o : orig) {
                for (Set<Object> s : runSet) {
                    Set<Object> s2 = new TreeSet<>();
                    s2.addAll(s);
                    s2.add(o);
                    powerSet.add(s2);
                    thisSet.add(s2);
                }
            }
            runSet.clear();
            runSet.addAll(thisSet);
            thisSet.clear();
        }
        powerSet.add(new TreeSet());
        return powerSet;
    

    Here's some example code to test:

    Set<Object> hs = new HashSet<>();
    hs.add(1);
    hs.add(2);
    hs.add(3);
    hs.add(4);
    for(Set<Object> s : powerSetofNodes(hs)) {
        System.out.println(Arrays.toString(s.toArray()));
    }
    
    0 讨论(0)
提交回复
热议问题