在 JavaScript 中有没有更好的方法来解决递归斐波那契
Is there a better way of solving recursive fibonacci in JavaScript
我想 return 给定数字的斐波那契数列;我想递归地这样做。
这是我的工作解决方案:
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)))
有没有办法在只使用一个函数的情况下摆脱条件(三元)运算符?
你可以试试这个。对于任何了解斐波那契数列的人来说,该代码几乎都是不言自明的。我正在嵌套对函数的递归调用,当它 returns 时,最后 2 个元素被添加并附加到数组。
var fibonacci = (num) => {
if (num <= 1)
return [1];
if (num === 2)
return [1, 1];
let arr = fibonacci(num-1);
let p1 = arr[arr.length-1];
let p2 = arr[arr.length-2];
return [...arr, p1+p2];
}
console.log(JSON.stringify(fibonacci(7)));
这就是我要做的。
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)));
就个人而言,我不喜欢使用默认参数。
我想 return 给定数字的斐波那契数列;我想递归地这样做。
这是我的工作解决方案:
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)))
有没有办法在只使用一个函数的情况下摆脱条件(三元)运算符?
你可以试试这个。对于任何了解斐波那契数列的人来说,该代码几乎都是不言自明的。我正在嵌套对函数的递归调用,当它 returns 时,最后 2 个元素被添加并附加到数组。
var fibonacci = (num) => {
if (num <= 1)
return [1];
if (num === 2)
return [1, 1];
let arr = fibonacci(num-1);
let p1 = arr[arr.length-1];
let p2 = arr[arr.length-2];
return [...arr, p1+p2];
}
console.log(JSON.stringify(fibonacci(7)));
这就是我要做的。
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)));
就个人而言,我不喜欢使用默认参数。