简体   繁体   English

查找此递归函数的时间复杂度

[英]Find time complexity of this recursive function

This algorithm is a bit nonsense because I reduced it to the basic scheme. 该算法有点废话,因为我将其简化为基本方案。

Basically, it takes a string as input, scan this string and create a new string that does not contain the first letter of the old string. 基本上,它将一个字符串作为输入,扫描该字符串并创建一个不包含旧字符串首字母的新字符串。 Is that a O(n^2)? 那是O(n ^ 2)吗? If you can justify the answer. 如果你能证明答案的合理性。 Thank you. 谢谢。

recursiveProc(String myString){
    if(myString.length() >= 1){
        char firstLetter = myString.charAt(0);
        String newString = "";

        for(int i = 0; i < myString.length(); i++){
            if(myString.charAt(i) != firstLetter){
                newString = newString + myString.charAt(i);
            }
        }
        recursiveProc(newString);
    }}

It's actually worse than O(N^2) . 实际上比O(N^2)还差。 Looks like O(N^3) . 看起来像O(N^3)

Each recursive call will reduce the input String by at least one character, so there would be at most N recursive calls (in the worst case there would be exactly N recursive calls, each reducing the input String by exactly one character). 每个递归调用将减少输入String至少一个字符,因此最多将有N递归调用(在最坏的情况下,将有N递归调用,每个递归调用将输入String减少一个字符)。

However, your loop takes O(N^2) , since it has O(N) iterations, and each iteration creates a new String whose length is not a constant. 但是,您的循环需要O(N^2) ,因为它具有O(N)次迭代,并且每次迭代都会创建一个长度不是常数的新String

Suppose you have the String "0123456789" 假设您有字符串“ 0123456789”

The first recursive call will remove the '0' character by creating the following String s: 第一次递归调用将通过创建以下String来删除“ 0”字符:

"1"
"12"
"123"
"1234"
"12345"
"123456"
"1234567"
"12345678"
"123456789"

This would take O(N^2) time. 这将花费O(N^2)时间。 And that's just the first recursive call. 那只是第一个递归调用。

You could improve it by using a StringBuilder instead of String concatenation to create the new String . 您可以通过使用StringBuilder而不是String串联来创建新的String

    StringBuilder sb = new StringBuilder(myString.length()-1);
    for(int i = 0; i < myString.length(); i++){
        if(myString.charAt(i) != firstLetter){
            sb.append(myString.charAt(i));
        }
    }
    recursiveProc(sb.toString());

In that case the loop would take O(N) (since each iteration of the loop does constant work) and the entire recursion would take O(N^2) . 在那种情况下,循环将采用O(N) (因为循环的每次迭代都进行恒定的工作),而整个递归将采用O(N^2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM