动态规划

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

上楼梯、斐波那契数列、泰波那契序列问题。

常规解法

1
function f (n) {if (n<=2) {return n;} return f(n-1)+f(n-2);}

闭包,memory cache

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var gen = () => {
let memory = [];
return function fib(n) {
if (n <= 1) {
return 1;
}
if (memory[n] > 0) {
return memory[n];
}
let num = fib(n-1) + fib(n-2);
memory[n] = num;
return num;
}
}

深度优先搜索

1
2
3
4
5
6
7
8
9
10
11
var fff = (n) => {
let memory = [0];
for(let i = 1; i <= n; i++) {
if (i <= 2) {
memory[i] = i;
} else {
memory[i] = memory[i-1] + memory[i-2];
}
}
return memory[n];
}