從斐波那契序列體會編程算法
1、純遞歸,巨慢
function F = fibo01(n)
% ? The recursion solution of the fibonacci sequence
% ? call the fibo(n) , n is a positive integer number
arguments
? ?n (1,1) {mustBeInteger,mustBePositive}
end
if n <= 2
? ?F = 1;
else
? ?F = fibo01(n-1)+fibo01(n-2);
end
end
2、加入備忘錄,自底向上,預分配內(nèi)存,空間換時間,快多了
function ?F = fibo02(n)
%The memo and End-Top Method of the fibonacci sequences
% ? call fibo02(n) to get the ans, n is a positive integer
arguments
? ?n (1,1) {mustBeInteger,mustBePositive}
end
memo = sym(ones(1,n)); ?% preallocate the memory and tradeoff space with time
if n <= 2
? ?F = memo(n);
else
? ?for i = 3:n
? ? ? ?memo(i) = memo(i-1)+ memo(i-2);
? ?end
? ?F = memo(n);
end
3、加入備忘錄,自頂向上,還是遞歸
function F = fibo03(n)
%the memo version of fibonacci sequences
% ? call fibo03(n) ,here n is a positive ?integer number
arguments
? ?n (1,1) {mustBeInteger,mustBePositive}
end
global memo
memo = sym(ones(1,n));
F = fibo_03(n);
end
function F = fibo_03(n)
%the memo version of fibonacci sequences
% ? call fibo03(n) ,here n is a positive ?integer number
arguments
? ?n (1,1) {mustBeInteger,mustBePositive}
end
global memo
if n<=2
? ?F = memo(n);
elseif memo(n) == 1
? ?memo(n) = fibo_03(n-1)+fibo_03(n-2);
? ?F = memo(n);
else
? ?F = memo(n);
end
end
4、雙指針,省時省空間
function F = fibo04(n)
%double pointer solution of fibonacci sequences
% ? call fibo04(n),n is a positive integer number here
arguments
? ?n (1,1) {mustBeInteger,mustBePositive}
end
a = sym(1); % initialize the two pointer
b = sym(1);
if n<=2
? ?F = 1;
else
? ?for i = 3:n
? ? ? ?c = a+b; ?% solve the i-th fabonacci
? ? ? ?a = b; ? ?% swap the a,b,c ,prepare for next interation
? ? ? ?b = c;
? ?end
? ?F = c;
end



很明顯,雙指針的速度要快很多,其次是向上模擬,然后是帶備忘錄的遞歸,最次是遞歸,根本算不出結果,由于使用了一些符號化以及輸入?yún)?shù)的限定,提高了魯棒性,同時也附加了額外的開銷
從斐波那契序列體會編程算法的評論 (共 條)
