Program to find how many ways we can climb stairs (maximum steps at most k times) in Python


Suppose we have a staircase with n steps and we also have another number k, initially we are at stair 0, and we can climb up either 1, 2 or 3 steps at a time. but we can only climb 3 stairs at most k times. Now we have to find the number of ways we can climb the staircase.

So, if the input is like n = 5, k = 2, then the output will be 13, as there are different ways we can climb the stairs −

  • [1, 1, 1, 1, 1]
  • [2, 1, 1, 1]
  • [1, 2, 1, 1]
  • [1, 1, 2, 1]
  • [1, 1, 1, 2]
  • [1, 2, 2]
  • [2, 1, 2]
  • [2, 2, 1]
  • [1, 1, 3]
  • [1, 3, 1]
  • [3, 1, 1]
  • [2, 3]
  • [3, 2]

To solve this, we will follow these steps −

  • if n is same as 0, then
    • return 1
  • if n is same as 1, then
    • return 1
  • k:= minimum of k, n
  • memo:= a matrix of size (n+1) x (k+1)
  • for r in range 0 to k, do
    • memo[r, 0]:= 1, memo[r, 1]:= 1, memo[r, 2]:= 2
  • for i in range 3 to n, do
    • memo[0, i]:= memo[0, i-1] + memo[0, i-2]
  • for j in range 1 to k, do
    • for i in range 3 to n, do
      • count := quotient of i/3
      • if count <= j, then
        • memo[j, i]:= memo[j, i-1] + memo[j, i-2] + memo[j, i-3]
      • otherwise,
        • memo[j, i]:= memo[j, i-1] + memo[j, i-2] + memo[j-1, i-3]
  • return memo[k, n]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n, k):
      if n==0:
         return 1
      if n==1:
         return 1
         k= min(k,n)
         memo=[[0]*(n+1) for _ in range(k+1)]
         for r in range(k+1):
            memo[r][0]=1
            memo[r][1]=1
            memo[r][2]=2
            for i in range(3,n+1):
               memo[0][i]=memo[0][i-1]+memo[0][i-2]
               for j in range(1,k+1):
                  for i in range(3,n+1):
                     count = i//3
                     if count<=j:
                        memo[j][i]=memo[j][i-1]+memo[j][i-2]+memo[j][i-3]
                     else:
                        memo[j][i]=memo[j][i-1]+memo[j][i-2]+memo[j-1][i-3]
         return memo[k][n]
ob = Solution()
print(ob.solve(n = 5, k = 2))

Input

5, 2

Output

13

Updated on: 05-Oct-2020

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements