n steps with 1, 2 or 3 steps taken. How many ways to get to the top?

前端 未结 13 761
时光说笑
时光说笑 2020-12-08 08:12

If we have n steps and we can go up 1 or 2 steps at a time, there is a Fibonacci relation between the number of steps and the ways to climb them. IF and ONLY if we do not co

13条回答
  •  有刺的猬
    2020-12-08 09:12

    Easily get the intuition for the problem:

    Think you are climbing stairs and the possible steps you can take are 1 & 2

    The total no. of ways to reach step 4 = Total no. of ways to reach step 3 + Total no of ways to reach step 2

    How?

    Basically, there are only two possible steps from where you can reach step 4.

    1. Either you are in step 3 and take one step
    2. Or you are in step 2 and take two step leap

    These two are the only possibilities by which you can ever reach step 4

    Similarly, there are only two possible ways to reach step 2

    1. Either you are in step 1 and take one step
    2. Or you are in step 0 and take two step leap

    F(n) = F(n-1) + F(n-2)

    F(0) = 0 and F(1) = 1 are the base cases. From here you can start building F(2), F(3) and so on. This is similar to Fibonacci series.

    If the number of possible steps is increased, say [1,2,3], now for every step you have one more option i.e., you can directly leap from three steps prior to it

    Hence the formula would become

    F(n) = F(n-1) + F(n-2) + F(n-3)

    See this video for understanding Staircase Problem Fibonacci Series

    Easy understanding of code: geeksforgeeks staircase problem

提交回复
热议问题