该图表展示了代码正在做什么以及从根本上讲斐波那契数是什么。
以下是该图表的工作原理:
fib(6)
。fib(x) = fib(x - 1) + fib(x - 2)
,然后fib(6) = fib(5) + fib(4)
如图所示通过向下移动的箭头。fib(5)
和fib(4)
。该图表显示了如何为它们重复上述过程(将它们分成更小的部分)。fib(2)
or fib(1)
,根据定义自动等于1
。1
将图表底部的所有s相加(有 8 个)。这与您的代码一起出现:
function fib(num1) {
// Start with a number (Step 1 on the chart).
if (num1 <= 2) {
// If it is <= 2, return 1 (Step 4 on the chart)
return num1 = 1;
} else {
// Break it down into smaller parts (Step 2 on the chart)
// and recursively repeat the process for the new parts (Step 3 on the chart).
return fib(num1 - 1) + fib(num1 - 2);
}
}
console.log(fib(6));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句