置换功能的运行时间

ran*_*534 5 java algorithm recursion performance permutation

我的书为函数提供了以下代码,该函数计算一串唯一字符的所有排列(请参见下面的代码),并说运行时间为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;
}
Run Code Online (Sandbox Code Playgroud)

资料来源:破解编码面试

inv*_*sal 3

从我们的直觉来看,很明显没有现有的算法可以生成比 O(n!) 更好的 N 个项目的排列,因为有 n! 可能性。

您可以将递归代码简化为递归方程,因为gePerm(n)其中 n 是长度为 n 的字符串,将调用getPerm(n-1). 然后,我们使用它返回的所有值并放置一个循环 N 次的内部循环。所以我们有

P n = nP n-1
P 1 = 1

容易看出P n = n!通过伸缩方程。


如果你很难想象我们是如何得出这个方程的,你也可以这样想

ArrayList<String> words = getPerms(remainder);
for (String word: words)                          // P(n-1)
{
    for (i = 0; i <= word.length(); i++)          // nP(n-1)
    {
        String s = insertCharAt(word, first, i);
        permutations.add(s)
    }
}
Run Code Online (Sandbox Code Playgroud)