- 暴力實現
function fibonacci(n) {
if (!(/^[1-9]\d*$/.test(n))) {
throw new Error("請輸入正整數!")
}
if (n == 0) return 0
if (n == 1) return 1
return fibonacci(n - 1) + fibonacci(n - 2)
}
- 閉包最佳化,加入快取(空間 換時間)
function fibonacci2() {
let cache = [0, 1, 1]
function fib(n) {
console.log(this);
if (cache[n]) {
return cache[n]
}
if (n <= 2) {
return cache[n];
}
var temp = fib(n - 1) + fib(n - 2);
cache[n] = temp;
return temp;
}
return fib;
}
- 時間換空間。for迴圈
function fibonacci4(n) {
var res1 = 1;
var res2 = 1;
var sum = res2;
for (var i = 2; i < n; i++) {
sum = res1 + res2;
res1 = res2;
res2 = sum;
}
return sum;
}
- 尾部最佳化遞迴呼叫
function fibonacci4(n, res1 = 1, res2 = 1) {
if (!(/^[1-9]\d*$/.test(n))) {
throw new Error("請輸入正整數!")
}
if (n <= 2) {
return res2;
} else {
return fibonacci4(n - 1, res2, res1 + res2);
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結