如果“LINE 3”为0,fib(n)需要多少次附加函数调用被删除了?
我刚刚在面试中遇到这个问题,不知道如何计算答案。
如果删除“LINE 3”,fib(n) 需要多少次附加函数调用?答案应该用n 表示。
int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
if(n == 2) return 1; //LINE 3 HERE <---
return fib(n - 1) + fib(n - 2);
}
I just got this question on an interview and had no idea how to calculate the answer.
How many additional function calls does fib(n) require if "LINE 3" is removed? The answer should be in terms on n.
int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
if(n == 2) return 1; //LINE 3 HERE <---
return fib(n - 1) + fib(n - 2);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可以很容易地计算出来。旧代码:
新代码:
只需将两者相减即可计算差异:
这意味着差异是从 0,0,2 开始的斐波那契数列。也可以为其计算封闭形式表达式。
It can be easily calculated. The old code:
The new code:
The difference is computed simply by subtracting those two:
Which means the difference is a Fibonacci sequence beginning with 0,0,2. It is also possible to calculate a closed form expression for it.
所需的额外调用次数也是斐波那契序列。
0 0 2 2 4 6 10 16 26 42 68 110 178 288 466
注意:我认为这会是一些常数,但是......
Number of extra calls required is also Fibonacci kind of sequence.
0 0 2 2 4 6 10 16 26 42 68 110 178 288 466
NOTE: I thought it would be some constant but...
假设没有第 3 行并计算 f(3):
现在需要 3 次调用来计算 f(2)。如果有第 3 行,那么这将在 1 次调用中完成。
该算法的复杂度(没有第三行)是
O(2^n)
。当您添加第 3 行时,其中包含n = 2
情况的显式解决方案,复杂度变为O(2^(n-1))
等于(1/2) * O(2^n)
=kO(2^n)
其中系数 k = 0.5。如果您为 n = 3 的情况添加显式解,那么您将得到 k = 0.25 等等。当您添加p
显式解决方案时,复杂度将为:这意味着,如果您计算从 1 到 n 的 n 的答案,并且保存所有计算出的解决方案,那么您将得到
p = n - 1
并且每个n
步骤的算法和复杂度将为2*O(n)
。Let's assume that there's no 3rd line and calculate f(3):
It takes 3 calls to calculate f(2) now. It there was a 3rd line then this will be done in 1 call.
The complexity of this algorithm (without 3rd line) is
O(2^n)
. When you add line 3, which contain explicit solution for the case whenn = 2
the complexity becomesO(2^(n-1))
what is equals to(1/2) * O(2^n)
=kO(2^n)
where koefficient k = 0.5. If you add explicit solution for the case where n = 3 then you get k = 0.25 and so on. When you addp
explicit solutions the complexity will be:This means that if you will calculate the answer for n from 1 to n and if you'll save all calculated solutions then you'll get
p = n - 1
and the algorithm for each ofn
steps and the comlexity will be2*O(n)
.