-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#0070 Climbing Stairs.py
34 lines (28 loc) · 1.04 KB
/
#0070 Climbing Stairs.py
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
class Solution:
def climbStairs(self, n: int) -> int:
"""
Calculate the number of distinct ways to climb a staircase with `n` steps,
where you can either take 1 or 2 steps at a time.
Args:
n (int): The total number of steps in the staircase.
Returns:
int: The number of distinct ways to reach the top.
"""
# Base cases stored in a memoization dictionary
memo = {1: 1, 2: 2}
def f(x: int) -> int:
"""
Recursive helper function to compute the number of ways to reach the `x`th step.
Args:
x (int): The current step.
Returns:
int: The number of ways to reach the `x`th step.
"""
if x in memo:
return memo[x]
else:
# Store the computed value in the memo dictionary
memo[x] = f(x - 2) + f(x - 1)
return memo[x]
# Start the computation from step `n`
return f(n)