我发现了这个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},{}}代码执行完毕后。

最佳答案

这可以用这种方式描述。


如果originalSet为空,则返回{}(因为空集的唯一子集是空集)。
将originalSet拆分为第一个元素(head)和所有其他元素(rest)。
我们将保留一个正在运行的集合(sets),这最终将是我们的答案。对于originalSet的每个不包含第一个元素的子集(rest的子集),请将其和一个包含所有元素加上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是原始集合的大小。

08-17 15:01