尾递归,为什么有效?

时间:2021-02-13 16:33:11

标签: c++ algorithm function recursion tail-recursion

我在看:https://www.youtube.com/watch?v=_JtPhF8MshA

以下实现:

int factorial (int n)
{
    if (n==0) return 1;
    return n * factorial(n-1);
}

具有以下内容:

int factorial (int n)
{
    return go(n, );
}

int go(int n, int a)
{
    if (n==0) return a;
    return go(n-1, a*n);
}

他声称第二种更有效,但我的问题是为什么?

两者调用函数的次数完全相同,因此其中 2 次是 O(n)。

0 个答案:

没有答案
相关问题