gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:51:12 29 4
gpt4 key购买 nike

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

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com