Skip to content

Commit 54d4320

Browse files
committed
70 - Climbing stairs
1 parent 0327965 commit 54d4320

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

70-climbing-stairs.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
// n = 2
6+
// 1 + 1
7+
// 2
8+
9+
// n = 3
10+
// 1 + 1 + 1
11+
// 1 + 2
12+
// 2 + 1
13+
14+
// n = 4
15+
// 1 + 1 + 1 + 1
16+
// 1 + 2 + 1
17+
// 2 + 1 + 1
18+
// 1 + 1 + 2
19+
// 2 + 2
20+
21+
// n = 5
22+
// 1 + 1 + 1 + 1 + 1
23+
// 1 + 1 + 1 + 2
24+
// 1 + 2 + 1 + 1
25+
// 1 + 1 + 2 + 1
26+
// 1 + 2 + 2
27+
// 2 + 1 + 1 + 1
28+
// 2 + 1 + 2
29+
// 2 + 2 + 1
30+
31+
// r = (n-1) + (n-2)
32+
const cache = [];
33+
var climbStairs = function (n) {
34+
if (cache[n]) {
35+
return cache[n];
36+
}
37+
38+
if (n <= 3) {
39+
cache[n] = n;
40+
return n;
41+
}
42+
43+
cache[n] = climbStairs(n - 2) + climbStairs(n - 1);
44+
return cache[n];
45+
};
46+
47+
console.log(climbStairs(1));

0 commit comments

Comments
 (0)