Skip to content

Commit 23bfc3d

Browse files
committed
2. climbing stairs
1 parent a57928c commit 23bfc3d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

climbing-stairs/whewchews.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
function climbStairs(n: number): number {
2+
/*
3+
* 아이디어
4+
* 층수 제한: 1 <= n <= 45
5+
* 1 or 2 step 만 올라갈 수 있음
6+
7+
* 1 -> [1]
8+
* 2 -> [1,1] [2]
9+
* 3 -> [1,1,1] [2,1] [1,2]
10+
* 4 -> [1,1,1,1] [2,1,1] [1,2,1] [1,1,2] [2,2]
11+
* 5 -> [1,1,1,1,1] [2,1,1,1] [1,2,1,1] [1,1,2,1] [1,1,1,2] [2,2,1], [1,2,2], [2,1,2]
12+
* 6 -> [1,1,1,1,1,1] [2,1,1,1,1] [...] [1,1,1,1,2] [2,2,1,1], [2,1,2,1], [2,1,1,2] [1,1,2,2], [1,2,1,2], [1,2,2,1]
13+
=> (1-n, 2-0) n가지 (1:n-2, 2:1) (n-1)*(n-2)/(n-2) 가지 (1: n-4, 2: n/2) (n-2)*(n-3)/2 가지
14+
*/
15+
16+
// # solution 1
17+
// TC: O(N)
18+
// SC: O(N)
19+
// const stair = {1: 1, 2:2}
20+
// for(let i = 3; i<=n; i++){
21+
// stair[i] = stair[i-1] + stair[i-2]
22+
// }
23+
24+
// # solution 2
25+
// TC: O(N)
26+
// SC: O(1)
27+
// if(n < 3) return n
28+
// let curr = 2
29+
// let prev = 1
30+
31+
// for(let i=0; i<n-2; i++){
32+
// const next = prev + curr;
33+
// prev = curr;
34+
// curr = next;
35+
// }
36+
37+
// return curr
38+
39+
// # Solution 3: 재귀
40+
// TC: O(N)
41+
// SC: O(N)
42+
const memo = { 1: 1, 2: 2 };
43+
function calculateClimbingWay(n, memo) {
44+
if (!(n in memo)) {
45+
if (n < 3) {
46+
return n;
47+
}
48+
memo[n] =
49+
calculateClimbingWay(n - 1, memo) + calculateClimbingWay(n - 2, memo);
50+
}
51+
return memo[n];
52+
}
53+
return calculateClimbingWay(n, memo);
54+
}

0 commit comments

Comments
 (0)