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

标签 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
    }
  }
}

最佳答案

每个permute(a,i,n)原因n-i调用 permute(a,i+1,n)

因此,当i == 0n打电话,当i == 1n-1调用...当i == n-1有一个电话。

你可以从这里找到一个迭代次数的递归公式:
T(1) = 1 [根据] ;和 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+1permute(a,i+1,n) ,导致 T(n) = (n+1) * T(n-1) [步骤] 和 T(0) = 1 [base],后来导致 T(n) = (n+1) * n * ... * 1 = (n+1)! .
然而,它似乎是一个实现错误而不是一个功能:\

关于c - 如何计算回溯算法的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308986/

相关文章:

c - "Saving"for循环中的当前状态稍后继续

java - 当必须通过姓名和号码访问时,存储电话簿的最佳数据结构

time-complexity - 您如何得出alpha-beta修剪的时间复杂度?

java - 暂停通过 JNI 运行的 native C 代码

无法使用 gcc 编译 ANSI C 代码

c - 通过图像名称获取进程的进程句柄

c - 如何将输入格式化为仅接受整数值

arrays - 区分排序算法

python - 代码的时间复杂度是多少?

algorithm - 计算递归算法的时间复杂度