简体   繁体   中英

Need help understanding the Triple Step dynamic programming / recursion question

I been trying to learn/understand more of dynamic programming / recursion, but I am not sure how to wrap my head around why this works. I am working on this

https://www.geeksforgeeks.org/count-ways-reach-nth-stair-using-step-1-2-3/

which has the solution in the link. I understand recursion to a point, but I am not understanding how the the structure of the program gives the result you want. I just, can't see why

return findStep(n - 3) +  
       findStep(n - 2) + 
       findStep(n - 1);   

solves this, or how someone would know it would give you all the possibilities.

The memorize part of the code is showed later, but I wanted to just show the basics.

any help is appreciate, thank you!

For the benefit of people who haven't followed your link, the problem you're trying to solve is to find how many different ways there are of ascending a staircase by hopping up 1, 2 or 3 steps at a time (in any combination).

Let's use the notation f ( x ) to represent the number of possible ways of climbing a staircase of x steps, and suppose you're at the bottom of a staircase with n steps. You have three options for your next move:

  • If you go up one step, then there will be f ( n -1) possible ways of climbing the stairs from your new position.

  • If you go up two steps, then there will be f ( n -2) possible ways of climbing the stairs from your new position.

  • If you go up three steps, then there will be f ( n -3) possible ways of climbing the stairs from your new position.

If all three of these actions are possible, then the value of f ( n ) must be equal to f ( n -1) + f ( n -2) + f ( n -3). This is the basis of the recursion algorithm. All you have to provide is the end-point:

  • f (1) = 1 (ascend 1 step)

  • f (2) = 2 (ascend 2 steps, or 1+1 steps)

  • f (3) = 4 (ascend 3 or 2+1 or 1+2 or 1+1+1 steps)

If you like, you could also add the condition that f (0) = 1 (ie, there is one way of not ascending a staircase). The code in the page you linked to seems to have folded the results for f (3) and f (0) together, but the results will be the same.

Since this recursive algorithm calls itself 3 times at each iteration, it will run very slowly unless you store the intermediate values of f ( x ). This is what memoization in dynamic programming is for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM