[英]How to calculate the time complexity of back tracking algorithm
使用过这个程序,如何计算回溯算法的时间复杂度?
/*
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)
导致ni
调用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)
[步骤]
得到总数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)!
。
但是,它似乎是一个实现错误,而不是一个功能:
一个简单的直觉就是会有n! 排列,你必须生成所有这些。 因此,您的时间复杂度至少为n! 因为你将不得不遍历所有n! 为了生成所有这些。 因此,时间复杂度为O(n!)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.