用过这个程序,如何计算回溯算法的时间复杂度?
/*
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 == 0
有n
打电话,当i == 1
有n-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+1
次permute(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/