国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

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








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

分享到微博請遵守國家法律
衢州市| 雷州市| 南漳县| 巩义市| 扬中市| 吉林市| 中宁县| 申扎县| 民权县| 盘锦市| 甘孜县| 新平| 海口市| 合川市| 当涂县| 垣曲县| 和硕县| 商水县| 融水| 上高县| 礼泉县| 霞浦县| 八宿县| 珲春市| 临高县| 石家庄市| 汉川市| 工布江达县| 苗栗县| 姜堰市| 建阳市| 巴中市| 卢龙县| 浦东新区| 六盘水市| 赤峰市| 文登市| 桂林市| 马龙县| 江孜县| 永登县|