var memory = {};
function fib(n){
if (n<=2) {
return 1;
}
if (memory[n]) {
return memory[n];
}
return memory[n] = fib(n-1) + fib(n-2);
}
function fibnocache(n){
if (n<=2) {
return 1;
}
return (fibnocache(n-1) + fibnocache(n-2));
}
function fib2(n) {
if (n <= 1) {
return n;
}
var prev = 0, current = 1;
var tmp;
for (var i = 1; i < n; i++) {
tmp = current + prev;
prev = current;
current = tmp;
}
return current;
}
console.time('fib')
fib(40);
console.timeEnd('fib')
console.time('fibnocache')
fibnocache(40);
console.timeEnd('fibnocache')
console.time('fib2')
fib2(40);
console.timeEnd('fib2')
复制