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

不打扰是莪最后的温柔 提交于 2019-11-29 16:54:07

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.

When there are no steps you just go through without climbing, which is the one and only one way. As is pointed out in one of the comments, it can be represented as ().

For n=3 function returns 4 but i can see only 3 cases i.e. (1,1,1), (1,2), (3).

There are actually 4 cases: (1,1,1), (1,2), (2,1), (3).

placeybordeaux

As Geobits said there is four ways to climb 3 stairs

(1,1,1),(1,2),(2,1),(3)

As for why it returns 1 when n==0, this is because whenever n==0 that means that you have found exactly 1 way to climb the stairs.

Lastly this algorithm will take a very long time if you put any high number in, if you are looking for a dynamic programming approach you should create a n sized array and initialize the first three entries as 1,2,4 and then iterate through the array starting and index 3, each time set the index to array[i-1] + array[i-2] + array[i-3]. This will do the minimal amount of computation but will use a huge amount of memory.

There is a better way where you only use a 1x3 sized array, but I will leave how to do that as an exercise for the user.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!