-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathwhewchews.ts
56 lines (47 loc) ยท 1.61 KB
/
whewchews.ts
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* ์์ด๋์ด
* ์ธต์ ์ ํ: 1 <= n <= 45
* 1 or 2 step ๋ง ์ฌ๋ผ๊ฐ ์ ์์
* 1 -> [1]
* 2 -> [1,1] [2]
* 3 -> [1,1,1] [2,1] [1,2]
* 4 -> [1,1,1,1] [2,1,1] [1,2,1] [1,1,2] [2,2]
* 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]
* 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]
=> (1:n, 2:0) n๊ฐ์ง (1:n-2, 2:1) / n๊ฐ์ง (1: n-4, 2: n/2) C(n, n/2) ๊ฐ์ง
*/
function climbStairs(n: number): number {
// # Solution 1
// const stair = {1: 1, 2:2}
// for(let i = 3; i<=n; i++){
// stair[i] = stair[i-1] + stair[i-2]
// }
// TC: O(N)
// SC: O(N)
// # Solution 2
// if(n < 3) return n
// let curr = 2 // ํ์ฌ ๊ณ๋จ์ ์ค๋ฅด๋ ๋ฐฉ๋ฒ ์
// let prev = 1 // ์ด์ ๊ณ๋จ์ ์ค๋ฅด๋ ๋ฐฉ๋ฒ ์
// for(let i=0; i<n-2; i++){
// const next = prev + curr;
// prev = curr;
// curr = next;
// }
// return curr
// TC: O(N)
// SC: O(1)
// # Solution 3: ์ฌ๊ท
const memo = { 1: 1, 2: 2 };
function calculateClimbingWay(n, memo) {
if (n in memo) return memo[n];
if (n < 3) {
return n;
}
memo[n] =
calculateClimbingWay(n - 1, memo) + calculateClimbingWay(n - 2, memo);
return memo[n];
}
return calculateClimbingWay(n, memo);
// TC: O(N)
// SC: O(N)
}