Count the number of ways to reach Nth stair by taking jumps of 1 to N
Given an integer N which depicts the number of stairs, the task is to count the number of ways to reach Nth stair by taking jumps of 1 to N.
Input: N = 2
Explanation: Two ways to reach are: (1, 1) & (2)
Input: N = 3
Input: N = 4
Approach: In this problem, the number of ways to reach the ith stair is:
Ways to reach ith stair = (Sum of ways to reach stairs 1 to i-1)+1
As for any stair before i, ith stair can be reached in a single jump. And +1 for jumping directly to i.
Now to solve this problem:
- Create a variable sum to store the number of ways to reach on a particular stair. Initialise it with 0.
- Run a loop from i=1 to i=N-1 and for each iteration:
- Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.
- Change sum to sum = sum + cur.
- Return sum + 1 after the loop ends as the answer to this problem.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...