最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

從斐波那契序列體會編程算法

2022-11-01 08:55 作者:永遠的修伊  | 我要投稿

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ù)的限定,提高了魯棒性,同時也附加了額外的開銷








從斐波那契序列體會編程算法的評論 (共 條)

使用qq登录你需要登录后才可以评论。
太原市| 高阳县| 呼和浩特市| 名山县| 顺平县| 沧源| 太白县| 辉南县| 娄烦县| 岑溪市| 库车县| 锦屏县| 偏关县| 丽江市| 建始县| 吉林省| 微博| 新兴县| 通榆县| 博乐市| 永州市| 葫芦岛市| 搜索| 密山市| 嘉禾县| 罗城| 金溪县| 溧水县| 芮城县| 鸡西市| 三门县| 泽州县| 获嘉县| 澄城县| 遂昌县| 海安县| 靖州| 兰溪市| 镇坪县| 迁安市| 凌源市|