小编Ahm*_*ail的帖子

计算字符串的所有排列(破解编码访谈,第VI章 - 例12)

在Gayle Laakman的书"Cracking the Coding Interview",第六章(Big O),例12中,问题表明,给定以下用于计算字符串排列的Java代码,需要计算代码的复杂性

public static void permutation(String str) {
    permutation(str, "");
}

public static void permutation(String str, String prefix) {
    if (str.length() == 0) {
        System.out.println(prefix);
    } else {
        for (int i = 0; i < str.length(); i++) {
            String rem = str.substring(0, i) + str.substring(i + 1);
            permutation(rem, prefix + str.charAt(i));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这本书假设既然会有n!排列,如果我们认为每个排列都是调用树中的一个叶子,其中每个叶子都附加到长度为n的路径上,那么就不会有n*n!树中的节点(即:调用次数不超过n*n!).

但节点的数量不应该是:

FOO +酒吧

因为调用的数量相当于节点的数量(请参阅Quinston Pimenta的视频Permutations Of String | Code Tutorial中的图).

如果我们遵循这个方法,节点的数量将是1(对于树的第一级/根)+3(对于第二级)+ 3*2(对于第三级)+ 3*2*1(对于第四/最低级别)

即:节点数= 3!/ 3!+ 3!/ 2!+ 3!/ …

java string big-o permutation time-complexity

10
推荐指数
1
解决办法
2143
查看次数

标签 统计

big-o ×1

java ×1

permutation ×1

string ×1

time-complexity ×1