Python Program to Count ways to reach the n’th stair
Last Updated :
15 Nov, 2022
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top.
Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the top. The diagram is taken from Easier Fibonacci puzzles
Python3
def fib(n):
if n < = 1 :
return n
return fib(n - 1 ) + fib(n - 2 )
def countWays(s):
return fib(s + 1 )
s = 4
print ( "Number of ways =" ,countWays(s))
|
Output:
Number of ways = 5
The time complexity of the above implementation is exponential (golden ratio raised to power n). It can be optimized to work in O(Logn) time using the previously discussed Fibonacci function optimizations.
Python3
def countWaysUtil(n, m):
if n < = 1 :
return n
res = 0
i = 1
while i< = m and i< = n:
res = res + countWaysUtil(n - i, m)
i = i + 1
return res
def countWays(s, m):
return countWaysUtil(s + 1 , m)
s, m = 4 , 2
print ( "Number of ways =" , countWays(s, m))
|
Output:
Number of ways = 5
Time complexity: O(2n)
Auxiliary Space: O(n)
Python3
def countWaysUtil(n, m):
res = [ 0 for x in range (n)]
res[ 0 ], res[ 1 ] = 1 , 1
for i in range ( 2 , n):
j = 1
while j< = m and j< = i:
res[i] = res[i] + res[i - j]
j = j + 1
return res[n - 1 ]
def countWays(s, m):
return countWaysUtil(s + 1 , m)
s, m = 4 , 2
print ( "Number of ways =" , countWays(s, m))
|
Output:
Number of ways = 5
Time Complexity: O(m*n)
Auxiliary Space: O(n)
Please refer complete article on Count ways to reach the n’th stair for more details!
Share your thoughts in the comments
Please Login to comment...