Recursion on staircase

后端 未结 4 1738
[愿得一人]
[愿得一人] 2021-01-03 14:08

I\'m trying to understand the solution provided in a book to the following question:

\"A child is running up a staircase with n steps and can hop either 1 step, 2 st

4条回答
  •  感动是毒
    2021-01-03 15:07

    To try and answer your first question, why it returns 1 instead of 0, say you're looking at a stair with 2 steps in total, the recursive call then becomes:

    countWaysDP(2 - 1, map) + countWaysDP(2 - 2, map) + countWaysDP(2 - 3, map);
    

    The second recursive call is the one where n becomes zero, that's when we have found a successful path, because from 2 steps, there's obviously a path of taking 2 steps. Now, if you write as you suggested:

    n == 1: return 1 
    

    you would not accept taking two steps from the two stepped stair! What the statement means is that you only count the path if it ends with a single step!

提交回复
热议问题