如何计算反向跟踪算法的时间复杂度

use*_*495 3 c algorithm time-complexity

使用过这个程序,如何计算回溯算法的时间复杂度?

/*
  Function to print permutations of string    This function takes three parameters:
  1. String
  2. Starting index of the string
  3. Ending index of the string.
*/ 
void swap (char *x, char *y)
{
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}

void permute(char *a, int i, int n)
{  
  int j;

  if (i == n)
    printf("%s\n", a);
  else
  {
    for (j = i; j <= n; j++)
    {
      swap((a+i), (a+j));
      permute(a, i+1, n);
      swap((a+i), (a+j)); //backtrack
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 11

每个都会permute(a,i,n)导致n-i调用permute(a,i+1,n)

因此,当i == 0n呼叫时i == 1,有n-1呼叫时...... i == n-1有一个呼叫时.

你可以从中找到迭代次数的递归公式:
T(1) = 1[base]; 和T(n) = n * T(n-1)[步骤]

结果总共 T(n) = n * T(n-1) = n * (n-1) * T(n-2) = .... = n * (n-1) * ... * 1 = n!

编辑:[小修正]:因为for循环中的条件是j <= n[而不是j < n],每个permute()实际上都是调用n-i+1次数permute(a,i+1,n),导致T(n)= (n+1) * T(n-1)[step]和T(0) = 1[base],后来导致T(n) = (n+1) * n * ... * 1 = (n+1)!.
但是,它似乎是一个实现错误,而不是一个功能:\