1
+ """
2
+ You are climbing a staircase. It takes n steps to reach
3
+ the top.
4
+
5
+ Each time you can either climb 1 or 2 steps. In how many
6
+ distinct ways can you climb to the top?
7
+
8
+ Example 1:
9
+ Input: n = 2
10
+ Output: 2
11
+ Explanation: There are two ways to climb to the top.
12
+ 1. 1 step + 1 step
13
+ 2. 2 steps
14
+
15
+ Example 2:
16
+ Input: n = 3
17
+ Output: 3
18
+ Explanation: There are three ways to climb to the top.
19
+ 1. 1 step + 1 step + 1 step
20
+ 2. 1 step + 2 steps
21
+ 3. 2 steps + 1 step
22
+
23
+ Constraints:
24
+ * 1 <= n <= 45
25
+ """
26
+
27
+ class Solution :
28
+ # O(2^n) solution, pure recursion (time limit exceeded)
29
+ # O(2^n) because we double the number of nodes in the
30
+ # recursion tree every time we increase n
31
+ #def climbStairs(self, n: int) -> int:
32
+ # if n < 0:
33
+ # return 0
34
+ # elif n == 0:
35
+ # return 1
36
+ #
37
+ # return self.climbStairs(n-1) + self.climbStairs(n-2)
38
+
39
+ # O(n) solution using memoization
40
+ # O(n) -> in fact O(2n+1) because if we increase
41
+ # n by 1, we add only 2 extra nodes in the recursion tree
42
+ #def climbStairs(self, n: int) -> int:
43
+ # return self.find(n, {})
44
+ #
45
+ #def find(self, n, d={}):
46
+ # if n in d:
47
+ # return d[n]
48
+ #
49
+ # if n < 0:
50
+ # return 0
51
+ # elif n == 0:
52
+ # return 1
53
+ #
54
+ # d[n] = self.find(n-1, d) + self.find(n-2, d)
55
+ #
56
+ # return d[n]
57
+
58
+ # O(n) solution, dynamic programming
59
+ # f(n) is f(n-1) + f(n-2) -> so if we start
60
+ # "collecting" results from f(1) and f(2) up to
61
+ # n, we will get the number of distinct ways for n
62
+ def climbStairs (self , n : int ) -> int :
63
+ r = [0 , 1 , 1 ] + (n - 1 ) * [0 ]
64
+
65
+ for i in range (1 , n ):
66
+ r [i + 1 ] += r [i ]
67
+ r [i + 2 ] += r [i ]
68
+
69
+ return r [n ]
0 commit comments