1
+ """
2
+ [Problem]
3
+ https://leetcode.com/problems/climbing-stairs/
4
+
5
+ [Brainstorming]
6
+ 한 번에 갈 수 있는 계단: 1 or 2
7
+ 갈 수 있는 경우의 수를 구해야 하는 문제
8
+ constraints: 1 <= n <= 45
9
+
10
+ n = 1, 1
11
+ n = 2, 2
12
+ n = 3, 3
13
+ n = 4, 5
14
+ ...
15
+ f(n) = f(n - 1) + f(n - 2)
16
+
17
+ [Plan]
18
+ 1. n + 1 크기의 list를 만든다.
19
+ 2. list[1] = 1, list[2] = 2를 대입한다.
20
+ 3. for-loop를 3부터 n까지 순회한다.
21
+ 3-1. Bottom-Top 방식으로 n까지 값을 채워간다.
22
+ 4. n값을 반환한다.
23
+
24
+ [Complexity]
25
+ Time: O(n)
26
+ Space: O(n)
27
+ """
28
+
29
+
30
+ class Solution :
31
+ def climbStairs (self , n : int ) -> int :
32
+ answer = [0 , 1 , 2 ]
33
+ for index in range (3 , n + 1 ):
34
+ answer .append (answer [index - 1 ] + answer [index - 2 ])
35
+
36
+ return answer [n ]
37
+
38
+ """
39
+ another solution
40
+ ref: https://www.algodale.com/problems/climbing-stairs/
41
+ [Summary]
42
+ Bottom Top 방식인데 공간을 최적화하여 접근
43
+ [Complexity]
44
+ Time: O(n)
45
+ Space: O(1) - Space Optimization
46
+
47
+ [Plan]
48
+ 1. prev = 1, cur = 2를 저장한다.
49
+ 2. for-loop를 순회한다. 3 to n + 1
50
+
51
+ """
52
+
53
+ def climbStairs2 (self , n : int ) -> int :
54
+ if n <= 3 :
55
+ return n
56
+
57
+ prev , cur = [2 , 3 ]
58
+ for index in range (4 , n + 1 ):
59
+ tmp = cur
60
+ cur = cur + prev
61
+ prev = tmp
62
+ return cur
63
+
64
+ """
65
+ another solution
66
+ ref: https://www.algodale.com/problems/climbing-stairs/
67
+ [Summary]
68
+ Top-Bottom으로 재귀적으로 접근
69
+ [Complexity]
70
+ Time: O(n)
71
+ Space: O(n)
72
+ """
73
+
74
+ def climbStairs3 (self , n : int ) -> int :
75
+ cache = {}
76
+
77
+ def dfs (num : int ) -> int :
78
+ nonlocal cache
79
+ if num <= 3 :
80
+ return num
81
+ if num in cache :
82
+ return cache [num ]
83
+ cache [num ] = dfs (num - 1 ) + dfs (num - 2 )
84
+ return cache [num ]
85
+
86
+ return dfs (n )
87
+
88
+
89
+ sol = Solution ()
90
+
91
+ # Normal Case
92
+ print (sol .climbStairs3 (2 ) == 2 )
93
+ print (sol .climbStairs3 (3 ) == 3 )
94
+ print (sol .climbStairs3 (4 ) == 5 )
95
+ print (sol .climbStairs3 (5 ) == 8 )
96
+ print (sol .climbStairs3 (38 ))
97
+ # Edge Case
98
+ print (sol .climbStairs3 (1 ) == 1 )
0 commit comments