C 如何计算回溯算法的时间复杂度

C 如何计算回溯算法的时间复杂度,c,algorithm,time-complexity,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;

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

/*
  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
    }
  }
}
/*
用于打印字符串排列的函数此函数采用三个参数:
1.一串
2.字符串的起始索引
3.字符串的结束索引。
*/ 
无效交换(字符*x,字符*y)
{
焦炭温度;
温度=*x;
*x=*y;
*y=温度;
}
无效排列(字符*a,整数i,整数n)
{  
int j;
如果(i==n)
printf(“%s\n”,a);
其他的
{
对于(j=i;j每个
permute(a,i,n)
导致
n-i
调用
permute(a,i+1,n)

因此,当
i==0
n
调用时,当
i==1
n-1
调用时……当
i==n-1
有一个调用时

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

导致总的
T(n)=n*T(n-1)=n*(n-1)*T(n-2)=……=n*(n-1)*……*1=n!


EDIT:[small correction]:因为for循环中的条件是
j一个简单的直觉是将有n!个置换,您必须生成所有置换。因此,您的时间复杂度至少为n!,因为您必须遍历所有n!才能生成所有置换。

因此,时间复杂度是O(n!)。

作为旁注,因为存在
n!
对象的
n
排列,如果OP的算法有任何其他复杂度,那将是相当令人惊讶的。