理解将数组切片为子数组的递归调用

时间:2014-05-12 03:42:19

标签: java recursion set arrays

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

1 个答案:

答案 0 :(得分:2)

这可以用这种方式描述。

  • 如果originalSet为空,则返回{}(因为空集的唯一子集是空集)。
  • 将originalSet拆分为第一个元素(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是原始集的大小。