我是新来的宝石,所以我这里大概做了非常错误的新手解决了斐波那契序列的程序无法正常工作的返回值,但我想谷歌搜索答案,不能图出这个代码给怪异行为的原因。此代码非常简单,并使用基本的动态编程将中间结果存储到散列,以便稍后用于加速计算。如预期中的Ruby在使用动态规划
$existingSequence = {0 => 1, 1 => 2}
def fib(n)
if $existingSequence.has_key? n
return $existingSequence.values_at n;
end
if n == 0
return 1;
elsif n == 1
return 2;
end
$existingSequence[n] = fib(n - 1) + fib(n - 2)
return $existingSequence[n];
end
n = fib(2)
puts n
我期望此代码来输出3,因为使一个呼叫到撒谎(1)和FIB(0),它们分别返回2和1,然后加入到为3但输出为1和2 。