Was it helpful?

Question

Program to find how many ways we can climb stairs in Python

PythonServer Side ProgrammingProgramming

Suppose we have a staircase with n steps, and we can climb up either 1 or 2 steps at a time. We have to define a function that returns the number of unique ways we can climb the staircase.

The order of the steps should not be changed, so each different order of steps counts as a way. If the answer is very large then mod the result by 10^9 + 7

So, if the input is like n = 5, then the output will be 8, as there are 8 unique ways −

  • 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

To solve this, we will follow these steps −

  • dp:= an array of size n+1, and fill with 0
  • dp[1]:= 1
  • for i in range 2 to n+1, do
    • dp[i]:= dp[i-1]+dp[i-2]
  • return last element of dp mod m

Let us see the following implementation to get better understanding −

Example

 Live Demo

m =(10**9)+7
class Solution:
   def solve(self, n):
      dp=[0 for _ in range(n+2)]
      dp[1]=1
      for i in range(2,n+2):
         dp[i]=dp[i-1]+dp[i-2]
      return dp[-1] % m
ob = Solution()
print(ob.solve(5))

Input

5

Output

8
raja
Published on 05-Oct-2020 15:50:04
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top