简体   繁体   English

这是对递归跟踪的解释,我无法理解其中的一些逻辑。 请帮我分析一下逻辑

[英]This is explanation on recursion tracing and i can't understand some logic in it. Please help me with the logic

在此处输入图片说明

The function written in this pic is for explaining recursion.这张图片中写的函数是为了解释递归。 It says that the function takes T(n) time to run but it contains a recursive call and then it takes T(n-1) time to run.它说该函数需要 T(n) 时间来运行,但它包含一个递归调用,然后它需要 T(n-1) 时间来运行。 But we know that function takes T(n) time and same function call is taken then it should again take T(n) time because function is doing same thing as before.但是我们知道函数需要 T(n) 时间并且执行相同的函数调用,然后它应该再次需要 T(n) 时间,因为函数和以前做同样的事情。 Please tell me if i am wrong in understanding the concept or the concept is wrongly explained in the code.请告诉我是我对概念的理解有误,还是代码中对概念的解释有误。

The image is this图片是这个

void Test(int n) {
    if (n > 0) {
        printf("%d",n);        // 1
        Test(n-1);             // T(n-1)
    }
}
// T(n) = T(n-1) + 1

By definition T(n) is the time taken by Test(n) .根据定义T(n)Test(n)所用的时间。 Also T(n-1) is just a label for "time taken to call Test(n-1) ".此外, T(n-1)只是“调用Test(n-1)花费的时间”的标签。

As the function only calls printf which is constant complexity, it is counted as 1 instruction, and calls Test(n-1) , its total runtime is T(n) = T(n-1) + 1 .由于该函数只调用具有常数复杂度的printf ,因此计为 1 条指令,并调用Test(n-1) ,其总运行时间为T(n) = T(n-1) + 1

But we know that function takes T(n) time and same function call is taken then it should again take T(n) time because function is doing same thing as before.但是我们知道函数需要 T(n) 时间并且执行相同的函数调用,然后它应该再次需要 T(n) 时间,因为函数和以前做同样的事情。

No, T(n-1) is not the same as T(n) because Test(n) is not doing the same as Test(n-1) .不, T(n-1)T(n)因为Test(n)Test(n-1) Test(n) is doing the same as Test(n-1) plus calling printf once. Test(n)的作用与Test(n-1)相同,外加一次调用printf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM