# 题目描述
实现斐波那契数列 —— 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
这个数列从第3项开始,每一项都等于前两项之和
# 代码实现
// 递归
function fib(n) {
if (n == 0 || n == 1) {
return n;
}
return fib(n - 2) + fib(n - 1);
}
// dp
function fib(n) {
if (n == 0 || n == 1) {
return n;
}
let a = 0,
b = 1;
for (let i = 2; i <= n; i++) {
let temp = a + b;
a = b;
b = temp;
}
return b;
}
for(let i = 0; i <= 10; i ++){
const res = fib(i);
process.stdout.write(res + ",");
}
// 0,1,1,2,3,5,8,13,21,34,55,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28