我想我觉得这有点混乱,因为我从来没有真正使用过Java集。有人能试着用下面的代码(ps我是从stackoverflow上的一篇文章中得到这段代码的,所以这个人值得称赞)给我看看吗(最好是通过解释powerset是如何逐渐创建的):
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,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} }
代码也在做同样的事情,使用递归生成较小的powerset,并在列表中累加每个set。