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

歡迎光臨散文網(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ù)的限定,提高了魯棒性,同時也附加了額外的開銷








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

分享到微博請遵守國家法律
南宫市| 于田县| 长泰县| 平陆县| 濮阳市| 广南县| 滨海县| 深圳市| 黄龙县| 葵青区| 赞皇县| 门源| 竹北市| 牙克石市| 平顺县| 邯郸县| 文水县| 西乌珠穆沁旗| 平武县| 博白县| 深圳市| 车险| 监利县| 新昌县| 安国市| 团风县| 偏关县| 高碑店市| 宁乡县| 武邑县| 周口市| 高尔夫| 阜宁县| 工布江达县| 梅河口市| 都江堰市| 柏乡县| 余庆县| 邹平县| 莱阳市| 桦川县|