这种排列算法的空间复杂性是什么?

时间:2016-11-14 07:16:55

标签: algorithm big-o permutation

这种递归计算排列的算法的时间复杂度应该是O(n!*n),但我不能100%确定空间复杂度。

递归n,递归所需的最大空间为n(每个排列的空间* n!(排列数)。算法的空间复杂度是多少`O(n!* n ^ 2)?

static List<String> permutations(String word) {
    if (word.length() == 1)
        return Arrays.asList(word);
    String firstCharacter = word.substring(0, 1);
    String rest = word.substring(1);
    List<String> permutationsOfRest = permutations(rest);
    List<String> permutations = new ArrayList<String>(); //or hashset if I don’t want duplicates
    for (String permutationOfRest : permutationsOfRest) {
        for (int i = 0; i <= permutationOfRest.length(); i++) {
            permutations.add(permutationOfRest.substring(0, i) +  firstCharacter + permutationOfRest.substring(i));
        }
    }
    return permutations;
}

1 个答案:

答案 0 :(得分:1)

不,空间复杂度是“只是”O( n !× n ),因为你不能同时保持所有递归调用'{{1} } / permutationsOfRest。 (你一次有两个,但这只是一个常数因子,因此与渐近复杂度无关。)

请注意,如果您实际上不需要 permutations,最好将其作为自定义List<String>实现包装起来,这样就不会需要立即将所有排列保留在内存中,并且在开始对任何排列进行任何操作之前不需要预先计算所有排列。 (当然,实现起来有点棘手,所以如果Iterator<String>的主要用途只是预先填充Iterator<String>,那就不值得了。)