递归
- 迭代求 fibonacci
function fib (n) {
if (n < 1) return 0
if (n <= 2) return 1
let fib_1 = 0
let fib_2 = 1
let fib_N = n
for (let i=2; i < n; i++>) {
fib_N = fib_1 + fib_2
fib_1 = fib_2
fib_2 = fib_N
}
return fib_N
}
- 递归求 fibonacci
function fib (n) {
if (n < 1) return 0
if (n <= 2) return 1
return fib(n-1) + fib(n-2)
}
- 记忆化斐波那契
function fib (n) {
const memo = [0, 1]
const fibon = n => {
if (memo[n] != null) return memo[n]
return momo[n] = fib(n-1, memo) + fib(n-2, memo)
}
return fibon
}