在一本书中,我遇到以下问题:
In a book I encountered following question:
给出N步台阶,如果使用1、2或3步,则可以攀登多少种方式一次?
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?
以下是书中给出的代码:
Following is the code that book has given:
int countWays(int n){ if(n<0) return 0; if(n == 0) return 1; else return countWays(n-1) + countWays(n-2) + countWays(n-3); }在理解此代码时,我有以下担忧:
I have the following concerns in understanding this code:
我不明白为什么对于n = 0返回1。如果有0个步骤,那么显然我们不必爬任何步骤,应该返回0。
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.
对于n = 3函数返回4,但我只能看到3种情况,即(1,1,1),(1,2),(3)。
For n=3 function returns 4 but i can see only 3 cases i.e. (1,1,1), (1,2), (3).
推荐答案
我不明白为什么对于n = 0返回1。如果有0个步骤,那么显然我们不必攀登任何一个,而应该返回为0。
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 ().
对于n = 3函数返回4,但我只能看到3种情况,即(1,1,1),(1,2),(3)。
For n=3 function returns 4 but i can see only 3 cases i.e. (1,1,1), (1,2), (3).
实际上有4种情况:(1,1,1),(1,2),(2,1),(3)。
There are actually 4 cases: (1,1,1), (1,2), (2,1), (3).
更多推荐
计算采取1、2或3步后n步的爬升方式
发布评论