在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!).
但节点的数量不应该是:
因为调用的数量相当于节点的数量(请参阅Quinston Pimenta的视频Permutations Of String | Code Tutorial中的图).
如果我们遵循这个方法,节点的数量将是1(对于树的第一级/根)+3(对于第二级)+ 3*2(对于第三级)+ 3*2*1(对于第四/最低级别)
即:节点数= 3!/ 3!+ 3!/ 2!+ 3!/ …