您好我正在尝试理解这个算法,并试图通过它来查看将产生什么值,但这样做并没有太多运气。我想我不知道我是否正确。这是算法
Algorithm Fast-Fibonacci(n)
Let fib[0] and fib[1] be 1.
for each i from 2 to n, do:
Let fib[i] be fib[i - 2] + fib[i - 1].
end of loop
return fib[n].
say Fast-Fib(5)
fib[0] = 0
Fib[1] = 1
fib[2] = {2-2] + [2-1] = 1
fib[3] = [3-2] + [3-1] = 3
fib[4] = 4-2] + [4-1] = 5
那么循环退出了吗? 导致 01135作为答案
答案 0 :(得分:2)
您正在访问fib
的元素,因此对于Fast-Fib(5)
,您会获得:
fib[0] = 1
fib[1] = 1
fib[2] = fib[2-2] + fib[2-1] = fib[0] + fib[1] = 1+1 = 2 // i==2
fib[3] = fib[3-2] + fib[3-1] = fib[1] + fib[2] = 1+2 = 3 // i==3
fib[4] = fib[4-2] + fib[4-1] = fib[2] + fib[3] = 2+3 = 5 // i==4
fib[5] = fib[5-2] + fib[5-1] = fib[3] + fib[4] = 3+5 = 8 // i==5
返回fib[5]
(即5)
注意:我根据问题初始条件更新了值(fib[0]
= fib[1]
= 1);经常fib[0]
= 0; fib[1]
= 1