- Related Questions & Answers
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to find to get minimum cost to climb at the top of stairs in Python?
- Program to count how many ways we can divide the tree into two trees in Python
- Program to check how many ways we can choose empty cells of a matrix in python
- Program to count how many ways we can cut the matrix into k pieces in python
- In how many ways we can concatenate Strings in Java?
- Program to find how many total amount of rain we can catch in Python
- In how many ways can we find a substring inside a string in javascript?
- In how many ways can we split a string in JavaScript?
- Program to find number of ways we can decode a message in Python
- Program to find number of ways we can split a palindrome in python
- How many ways can we read data from the keyboard in Java?
- Program to find number of ways we can arrange symbols to get target in Python?
- Program to find number of ways we can concatenate words to make palindromes in Python
- What are JSP declarations? In how many ways we can write JSP declarations?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

5

8

Advertisements