What is the time complexity of this recursion function

时间:2015-07-31 19:27:39

标签: c++ c algorithm performance recursion

I encountered the following code which is used to get the longest common subsequence of two given strings. It uses recursion and the time complexity was given as 2^n, but I don't know how this result was generated, can anybody help analyzing it, thanks.

/* A Naive recursive implementation of LCS problem */
#include<stdio.h>
#include<stdlib.h>

int max(int a, int b);

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
   if (m == 0 || n == 0)
     return 0;
   if (X[m-1] == Y[n-1])
     return 1 + lcs(X, Y, m-1, n-1);
   else
     return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

/* Utility function to get max of 2 integers */
int max(int a, int b)
{
    return (a > b)? a : b;
}

/* Driver program to test above function */
int main()
{
  char X[] = "AGGTAB";
  char Y[] = "GXTXAYB";

  int m = strlen(X);
  int n = strlen(Y);

  printf("Length of LCS is %d\n", lcs( X, Y, m, n ) );

  getchar();
  return 0;
}

1 个答案:

答案 0 :(得分:1)

At worst, a call to lcs will cause two calls to lcs:

 return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

Also, if I=m+n then, the child calls always satisfy I_child <= I_parent - 1, cf the arguments of the possible recursive calls:

return 1 + lcs(X, Y, m-1, n-1);

and

return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));

so if C(I) is the complexity of lcs(X, Y, m, n), C(I) <= 2C(I - 1)+O(1)(set aside the recursive call, you're only performing comparisons which can be made in constant time as long as the integers are bounded, and they are, actually also jumps because of the if statements but you can also assume it's constant time)
so we have:

C(0) = O(1)
C(I) <= 2C(I - 1) + O(1) <= O(1) + 2O(1) + 2^2O(1)+....+2^IO(1)

hence

C(I) = O(2^I)

or in terms of m and n:

C(I) = O(2^max(m, n))

(Edit: this bound may be improved)