-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathways_to_climb_stairs.py
73 lines (53 loc) · 1.46 KB
/
ways_to_climb_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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
There are n stairs, a person standing at the bottom wants to reach the top.
The person can climb an array of possible steps at a time.
Count the number of ways, the person can reach the top.
10
/ | \
8 5 9
/ | \
0 -> one way
"""
# Tabular
def staircase_tabular(n, possible_steps):
T = [0] * (n + 1)
T[0] = 1
for i in range(1, n + 1):
for step in possible_steps:
if i - step >= 0:
T[i] += T[i - step]
return T[n]
# Memoization
memo = dict()
def staircase_memo(n, possible_steps):
if n == 0:
memo[n] = 1
return 1
if memo.get(n):
return memo[n]
ways = 0
for steps in possible_steps:
if n - steps >= 0:
ways += staircase_memo(n - steps, possible_steps)
memo[n] = ways
return ways
# Recursive
def staircase_recursive(n, possible_steps):
if n == 0:
return 1
ways = 0
for steps in possible_steps:
if n - steps >= 0:
ways += staircase_recursive(n - steps, possible_steps)
return ways
def test(n, possible_steps, expected_answer):
answer = staircase_tabular(n, possible_steps)
if answer != expected_answer:
raise Exception(
f"Answer {answer} is incorrect! Expected answer was {expected_answer}"
)
if __name__ == "__main__":
test(0, [1, 2, 3], 1)
test(10, [2, 4, 5, 8], 11)
test(100, [2, 4, 5, 8], 239633692743365)
print("All tests passed!")