首页 > 解决方案 > 有没有更好的方法来解决 JavaScript 中的递归斐波那契

问题描述

我想返回给定数字的斐波那契数列;我想递归地这样做。

这是我的工作解决方案:

function fibonacci(number, previous = 0, current = 0, index = 1) {
    if (index === number) {
        return [current + previous]
    }

    return [(index < 3) ? 1 : current + previous]
    .concat(fibonacci(number, current, (index < 3) ? 1 : current + previous, index + 1))
}

console.log(JSON.stringify(fibonacci(7)))

有没有办法在只使用一个函数的同时摆脱条件(三元)运算符?

标签: javascriptalgorithmfibonacci

解决方案


这就是我会做的。

const fibs = (a, b, n) => n > 0 ? [a, ...fibs(b, a + b, n - 1)] : [];

const fibonacci = n => fibs(1, 1, n);

console.log(JSON.stringify(fibonacci(7)));

您也可以使用默认参数。

const fibonacci = (n, a = 1, b = 1) =>
    n > 0 ? [a, ...fibonacci(n - 1, b, a + b)] : [];

console.log(JSON.stringify(fibonacci(7)));

就个人而言,我不喜欢使用默认参数。


推荐阅读