【问题标题】:How to calculate the time complexity of back tracking algorithm如何计算回溯算法的时间复杂度
【发布时间】:2024-01-19 04:48:02
【问题描述】:

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

/*
  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
    }
  }
}

【问题讨论】:

    标签: c algorithm time-complexity


    【解决方案1】:

    每个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 &lt;= n [而不是 j &lt; n],每个 permute() 实际上是在调用 n-i+1permute(a,i+1,n) ,导致 T(n) = (n+1) * T(n-1) [step] 和 T(0) = 1 [base],后来导致 T(n) = (n+1) * n * ... * 1 = (n+1)!
    但是,这似乎是一个实现错误,而不是一个功能:\

    【讨论】:

    • 作为旁注,因为有 n! 排列的 n 对象,如果 OP 的算法有任何其他复杂性,那将是相当令人惊讶的。
    【解决方案2】:

    一个简单的直觉是会有n!排列,您必须生成所有排列。因此,您的时间复杂度至少为 n!因为你必须遍历所有 n!为了生成所有这些。 因此,时间复杂度为 O(n!)。

    【讨论】: