一、递归算法
function recurFib(n) {
if (n < 2) {
return n;
}
else {
return recurFib(n-1) + recurFib(n-2);
}
}
alert(recurFib(10));//将显示55
二、动态规划法
function dynFib(n) {
var val = [];
for (var i = 0; i <= n; ++i) {
val[i] = 0;
}
if (n == 1 || n == 2) {
return 1;
}
else {
val[1] = 1;
val[2] = 2;
for (var i = 3; i <= n; ++i) {
val[i] = val[i-1] + val[i-2];
}
return val[n-1];
}
}
alert(dynFib(10));//将显示55
三、迭代法
function iterFib(n){
var last=1;
var nextlast=1;
var result=1;
for(var i=2;i<n;++i){
result=last+nextlast;
nextlast=last;
last=result;
}
return result;
}
alert(iterFib(10));//将显示55