Recursion 下列函数的空间复杂度是多少?如何计算?
考虑下面的递归函数Recursion 下列函数的空间复杂度是多少?如何计算?,recursion,big-o,space-complexity,Recursion,Big O,Space Complexity,考虑下面的递归函数 int f(int n){ if(n<=0) return 1; return f(n-1)+f(n-1); } intf(intn){ 如果(n确定。复杂性部分在else部分: 这会为n处的每个调用在n-1处生成两个调用。但是,请注意求值顺序: call f(n-1) ... left side save the value as temp1 call f(n-1) ... right side add the value to temp1 return th
int f(int n){
if(n<=0) return 1; return f(n-1)+f(n-1);
}
intf(intn){
如果(n确定。复杂性部分在else部分:
这会为n处的每个调用在n-1处生成两个调用。但是,请注意求值顺序:
call f(n-1) ... left side
save the value as temp1
call f(n-1) ... right side
add the value to temp1
return that value
在右侧调用树开始之前,必须完成整个左侧调用树——这在每个深度级别都会发生。对于n的每个值,在任何时间点都只有一个调用处于活动状态。例如,f(2)给出了如下序列:
call f(2)
n isn't <= 0 ...
call f(1) ... left
n isn't <= 0 ...
call f(0) ... left | left
n <= 0; return 1
save the 1
call f(0) ... left | right
n <=0; return 1
add the 1 to the temp value;
return 2
save the 2
call f(1) ... right
call f(0) ... left | left
n <= 0; return 1
save the 1
call f(0) ... left | right
n <=0; return 1
add the 1 to the temp value;
return 2
add this 2 to the temp value, making 4
return the 4
done ...
呼叫f(2)
n不是对于每个n
,f(n-1)
被调用两次。因此,如果您绘制一个根为n
的树,并为每个f(n-1)
的调用添加一个分支,以此类推,您将看到一个完整的高度为n
的二叉树,它有2^n个节点(调用总数)。
但需要注意的是,如果不先完成第一次调用并返回结果,就无法启动对f(n-1)
的第二次调用。对于f(n-2)
调用,在f(n-1)
最坏的情况(我假设这就是您正在寻找的)发生在您的函数调用集到达f(0)
并且您位于调用树的一个叶子上时。您的调用堆栈中有一组函数调用,它们从f(n-1)
,f(n-2)
,…,f(1)
,f(0)开始
。因此,在每个时间点,堆栈中最多有O(n)个函数(等于调用树的高度)。完美的解释。谢谢。感谢您的努力。很高兴能提供帮助。@javad也做得很好。记住“接受”答案(最终)所以StackOverflow可以优雅地将其淘汰。明白了。谢谢。感谢您的努力。但为了完整起见:所描述算法的空间复杂度仍然是O(N^2),而不是O(N)这是因为当右递归调用占用空间时,左递归调用的内存可能未被清理,还是有其他解释?这是因为返回值随着2^N的增加而增加。要存储此值,至少需要O(N)个空间。由于需要存储其中的O(N)个值,所以总复杂度为O(N^2)。
call f(2)
n isn't <= 0 ...
call f(1) ... left
n isn't <= 0 ...
call f(0) ... left | left
n <= 0; return 1
save the 1
call f(0) ... left | right
n <=0; return 1
add the 1 to the temp value;
return 2
save the 2
call f(1) ... right
call f(0) ... left | left
n <= 0; return 1
save the 1
call f(0) ... left | right
n <=0; return 1
add the 1 to the temp value;
return 2
add this 2 to the temp value, making 4
return the 4
done ...