Problem: Staircase (1)
Course: Recursion - chapter 6
You have N stairs in front of you. At every step, you can either climb up by 1, 2 or 3 stairs. How many ways are there to climb to the top?
Solution
Section titled “Solution”Let’s follow the 3 step approach for solving this:
- Identify the function and states:
f(i) = Number of ways to climb to the top if we are at ith stairThen, f(0) is the answer to the problem
- Assume, f(i) is calculated for every i except i = k.
- Try calculating f(k) We are at kth stair, what can we do. Either we can go to k+1 or k+2 or k+3. Now f(k+1) → No of ways to climb to top from (k+1)th stair Similarly, we have f(k+2) and f(k+3). As per step 2, these are calculated already, so what will be f(k)?
- Either we can go to k+1 and climb to top in f(k+1) ways
- Or we can go to k+2 and climb up in f(k+2) ways
- Or, go to k+3 and climb up in f(k+3) ways
So total ways:
f(k+1) + f(k+2) + f(k+3)