我发现这个java代码片段将数组切割成它的所有子集。但我无法理解递归调用的工作方式以及子集的形成方式。集合{1,2,3}的解释将非常有用。提前谢谢!
public static Set<Set<Integer>> powerSet(Set<Integer> originalSet) {
Set<Set<Integer>> sets = new HashSet<Set<Integer>>(); //All the subsets will be stored in sets.
if (originalSet.isEmpty()) {
sets.add(new HashSet<Integer>());
return sets;
}
List<Integer> list = new ArrayList<Integer>(originalSet);
int head = list.get(0);
Set<Integer> rest = new HashSet<Integer>(list.subList(1, list.size()));
for (Set<Integer> set : powerSet(rest)) {
Set<Integer> newSet = new HashSet<Integer>();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
return sets;
}
设置自身是一个集合,它包含{{1},{1,2},{1,3},{2,3},{2},{3},{1,2,3}, {}}代码完成后执行。
答案 0 :(得分:2)
这可以用这种方式描述。
{}
(因为空集的唯一子集是空集)。head
)和所有其他元素(rest
)。sets
)。对于不包含第一个元素(rest
的子集)的originalSet的每个子集,将它和一个包含其所有元素加上head
的集合放入我们的集合中。 {1, 2, 3}
的示例:
We want to find the power set of {1, 2, 3}.
In order to do this, we take off 1 and find the power set of {2, 3}.
In order to do this, we take off 2 and find the power set of {3}.
In order to do this, we take off 3 and find the power set of {}.
Which is {}.
For everything above ({}), copy it over, then copy it over but add a 3.
We have {{}, {3}}.
For everything above ({}, {3}), copy it over, then copy it over but add a 2.
We have {{}, {3}, {2}, {2, 3}}.
For everything above ({}, {3}, {2}, {2, 3}), copy it over, then copy it over but add a 1.
We have {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}.
请注意,应始终有2^n
个元素,其中n
是原始集的大小。