Obtaining a powerset of a set in Java

后端 未结 26 2095
青春惊慌失措
青春惊慌失措 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 11:47

    A sub-set of t is any set that can be made by removing zero or more elements of t. The withoutFirst subset adds the subsets of t that are missing the first element and the for loop will deal with adding subsets with the first element. For example, if t contained the elements ["1", "2", "3"], missingFirst will add [[""], ["2"], ["3"], ["2","3"]] and the for loop will stick the "1" in front of these element and add it to the newSet. So we'll end up with [[""], ["1"], ["2"], ["3"], ["1", "2"], ["1", "3"], ["2","3"], ["1", "2", "3"]].

    public static Set> allSubsets(Set t) {
            Set> powerSet = new TreeSet<>();
            if(t.isEmpty()) {
                powerSet.add(new TreeSet<>());
                return powerSet;
            }
            String first = t.get(0);
            Set> withoutFirst = allSubsets(t.subSet(1, t.size()));
            for (List 1st : withoutFirst) {
                Set newSet = new TreeSet<>();
                newSet.add(first);
                newSet.addAll(lst);
                powerSet.add(newSet);
            }
            powerSet.addAll(withoutFirst);
            return powerSet;
        }
    

提交回复
热议问题