Counting ways to climb n steps with 1, 2, or 3 steps taken

前端 未结 3 1091
耶瑟儿~
耶瑟儿~ 2020-12-21 20:57

In a book I encountered following question:

Given N step stair, in how many number of ways can you climb if you use either 1, 2 or 3 steps at a time?

Follow

3条回答
  •  萌比男神i
    2020-12-21 21:31

    I do not understand why 1 is being returned for n=0. If there are 0 steps then obviously we do not have to climb any and 0 should be returned.

    To complement the answer by Terry, the general answer to the problem is the tribonacci(n+2) sequence. Accordingly, for n=0, i.e. tribonacci(2), the value is 1. This is just a computational hack for the stairs problem, one that works. For a more thorough investigation, please see this answer.

    You can certainly choose to reject f(n=0) = 1. If you do, you can then just use the following base case values which you will be more comfortable with. All n>3 will be recursed to these base cases.

    • f(n=1) = 1
    • f(n=2) = 2
    • f(n=3) = 4

提交回复
热议问题