我正在编写一个简单的程序来递归地查找某个较大集合的所有子集。我已经成功了,但我想按尺寸顺序订购所有套装。
我在下面发布了我的工作代码。
import java.util.*;
public class AllSubsets {
public static void main(String[] args) {
// Change contents of this array to easily change contents of set.
Integer[] setContents = {3, 6, 8, 9, 10, 22};
// create initial unused set by dumping all of the aray into a set.
Set<Integer> unused = new HashSet<Integer>(Arrays.asList(setContents));
// create initial empty set for used set.
Set<Integer> used = new HashSet<Integer>();
// create output set of sets.
Set<Set<Integer>> allSets = new HashSet<Set<Integer>>();
allSets.add(used);
// find all sets recursively
findAllSets(used, unused, allSets);
// print out results
System.out.println(allSets);
}
public static void findAllSets(Set<Integer> used, Set<Integer> unused,
Set<Set<Integer>> allSets) {
if (unused != null) {
Set<Integer> copyOfUnused = new HashSet<Integer>(unused);
for (Integer val : copyOfUnused) {
unused.remove(val);
used.add(val);
allSets.add(new HashSet<Integer>(used));
findAllSets(used, unused, allSets);
used.remove(val);
unused.add(val);
}
}
}
}
我想知道按尺寸订购这些套装的最佳方法是什么。我尝试创建一个 TreeSet,其中包含多个 HashSet 对象,并覆盖其比较器方法。这最终编译但没有正确存储值。我编写的代码与上面的代码非常相似,因此我将在下面写出主要区别:
Set<Set<Integer>> allSets =
new TreeSet<Set<Integer>>(new Comparator<Set<Integer>>() {
public int compare(Set<Integer> a, Set<Integer> b) {
return a.size() - b.size();
}
});
在此版本的代码中,它可以编译,但对象未正确存储。正在计算正确的集合并将其添加到递归方法中的“allSets”中(使用 println 进行测试),但它一次只保存一组。我有一种感觉,这主要是因为我覆盖了 Set 的比较器,但我使用的是 HashSets。有没有更好的方法来组织我的集合,或者可能只是我的代码中的一个小错误?
谢谢!!
最佳答案
TreeSet<Set<Integer>>
只会存储一个给定大小的 Set 元素,因为它认为两个具有相同大小的不同集合“相等”:它需要 a.compareTo(b) == 0
意思是a == b
。
如果您想获取所有集合,然后按大小顺序打印它们,请将所有集合收集到常规(哈希)集合中,然后对条目进行排序:
List<Set<Integer>> listOfSets = new ArrayList<>(allSets);
Collections.sort(listOfSets, <your comparator above>);
System.out.println(listOfSets).
关于java - 在Java中按大小组织一组集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336234/