为了计算fibonacci序列的第n项,我有一个熟悉的递归函数:
var fibonacci = function(index){
if(index<=0){ return 0; }
if(index===1){ return 1; }
if(index===2){ return 2; }
return fibonacci(index-2) + fibonacci(index-1);
}这如预期的那样起作用。现在,我试图将计算出来的索引存储在一个对象中:
var results = {
0: 0,
1: 1,
2: 2
};
var fibonacci = function(index){
if(index<=0){ return 0; }
if(index===1){ return 1; }
if(index===2){ return 2; }
if(!results[index]){
results[index] = fibonacci(index-2) + fibonacci(index-1);
}
}我知道这实际上并没有提高性能,因为我没有访问结果对象,但我想先检查我的结果对象在回忆录之前是否被正确填充。不幸的是,事实并非如此。对于fibonacci(9),我得到:
Object {0: 0, 1: 1, 2: 2, 3: 3, 4: NaN, 5: NaN, 6: NaN, 7: NaN, 8: NaN, 9: NaN}为什么我得到的指数NaN超过3?
发布于 2016-02-13 23:12:10
通过发布@Juhana的评论来结束这个答案的循环:
“因为当索引>2时,函数不会返回任何内容”
发布于 2020-10-26 04:46:29
这是我的解决方案:
function fib(n, res = [0, 1, 1]) {
if (res[n]) {
return res[n];
}
res[n] = fib(n - 1, res) + fib(n - 2, res);
return res[n];
}
console.log(fib(155));发布于 2021-09-03 11:56:19
下面是使用"Helper Method Recursion“的解决方案:
function fib(n) {
const memorize = {};
function helper(n) {
if (n in memorize) return memorize[n];
if (n < 3) return 1;
return memorize[n] = helper(n - 1) + helper(n - 2);
}
return helper(n);
}https://stackoverflow.com/questions/33861501
复制相似问题