【发布时间】:2015-08-01 05:55:52
【问题描述】:
我的书为计算一串唯一字符的所有排列的函数提供了以下代码(参见下面的代码),并说运行时间为 O(n!),“因为有 n! 个排列。 "
我不明白他们如何将运行时间计算为 O(n!)。我假设他们的意思是“n”是原始字符串的长度。我认为运行时间应该是O((n + 1)XY),因为getPerms函数会被调用(n + 1)次,而X和Y可以代表外层和内层for循环的运行时间分别。有人可以向我解释为什么这是错误的/这本书的答案是正确的吗?
谢谢。
public static ArrayList<String> getPerms(String str)
{
if (str == null)
return null;
ArrayList<String> permutations = new ArrayList<String>();
if (str.length() == 0)
permutations.add("");
return permutations;
char first = str.charAt(0); //first character of string
String remainder = str.substring(1); //remove first character
ArrayList<String> words = getPerms(remainder);
for (String word: words)
{
for (i = 0; i <= word.length(); i++)
{
String s = insertCharAt(word, first, i);
permutations.add(s)
}
}
return permutations;
}
public static String insertCharAt(String word, char c, int j)
{
String start = word.substring(0, i);
String end = word.substring(i);
return start + c + end;
}
来源:Cracking the Coding Interview
【问题讨论】:
-
@shekharsuman 这是书中提供的唯一代码。我同意它不完整。
标签: java performance algorithm recursion permutation