Last active
August 29, 2015 14:15
-
-
Save hendawy/ed7ef6fc12558913a93d to your computer and use it in GitHub Desktop.
How many ways to climb n numbers of stairs if you could climb them 1, 2, 3 flights at a time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
How many ways to climb n numbers of stairs if you could climb them 1, 2, 3 | |
flights at a time | |
""" | |
def stairs(num): | |
""" | |
This solution depends on how many ways I could get to any flight of staits. | |
When I could reach a flight (i) with n ways and I could reach flight (i + 1) | |
with (m) ways without passing by flight (i), then the total way of reaching | |
flight (i + 1) is (n + m) | |
Time complexity = O(n) | |
Space complexity = O(n) | |
""" | |
# Rejecting any number of flights if its <= 0 | |
if num <= 0: | |
return 0 | |
# Initializing a list. List[0] is before taking any steps | |
steps, moves = [0 for i in range(num + 1)], [1, 2, 3] | |
for i in range(0, num): | |
ways = max(1, steps[i]) | |
for m in moves: | |
if i + m <= num: | |
steps[i + m] += ways | |
return steps[num] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment