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