题解 | #斐波那契数列#
斐波那契数列
https://www.nowcoder.com/practice/aa8ffe28ec7c4050b2aa8bc9d26710e9
//第一种方法,可以用普通for循环的方式
function fibonacci(n) {
let num1 = 1;
let num2 = 1;
for (var i = 2; i < n; i++) {
let num = num1
num1 = num2
num2 = num1 + num
}
return num2
}
let num1 = 1;
let num2 = 1;
for (var i = 2; i < n; i++) {
let num = num1
num1 = num2
num2 = num1 + num
}
return num2
}
//第二种方法,可以用递归的方式
function fibonacci(n) {
if (n <= 2) return 1
return fibonacci(n - 1) + fibonacci(n - 2)
}
if (n <= 2) return 1
return fibonacci(n - 1) + fibonacci(n - 2)
}