简体   繁体   English

楼梯问题——理解基本逻辑

[英]Staircase Problem - understanding the basic logic

Here is the recursive version of the staircase problem (There are N stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 stair, 2 stairs or 3 stairs at a time. Count the number of different ways the person can reach the top.)这是楼梯问题的递归版本(有 N 个楼梯,站在底部的人想要到达顶部。这个人一次可以爬 1 个楼梯、2 个楼梯或 3 个楼梯。计算不同方式的数量该人可以到达顶部。)

public static int findStep(int n) 
    { 
        if (n == 1 || n == 0)  
            return 1; 
        else if (n == 2)  
            return 2; 

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

My question is, why we are returning 1 when n=0??我的问题是,为什么我们在 n=0 时返回 1?

To me, n=0 means there are no more stairs so it should return 0, but if I do so then the program doesn't work for other non-zero inputs.对我来说,n=0 意味着没有更多的楼梯,所以它应该返回 0,但如果我这样做了,那么程序就不适用于其他非零输入。 I saw similar questions in this site but non of those explain why we are returning 1 when there are no more stairs.我在这个网站上看到了类似的问题,但没有一个可以解释为什么我们在没有更多楼梯的情况下返回 1。

This is a selection problem.这是一个选择问题。 Think of the recurrence as the number of ways to select and order a combination of zero or more 1's, zero or more 2's, and zero or more 3's, that will together sum to n .将递归视为 select 的方法数,并订购零个或多个 1、零个或多个 2 和零个或多个 3 的组合,它们总和为n There is only one way to make such a selection for n = 0 : select none.对于n = 0只有一种方法可以选择:select none。

In this code n=0 means in the last step n was equal to 1 or 2 or 3 .在此代码中n=0表示在最后一步中n等于123 in other words:换句话说:

n-1=0 which means in the last step n=1 , so there is one way to reach the top of stairs. n-1=0这意味着在最后一步n=1 ,所以有一种方法可以到达楼梯的顶部。

n-3=0 which means in the last step n=3 , so one way to reach the top of stairs is to make 3 steps. n-3=0表示在最后一步n=3 ,因此到达楼梯顶部的一种方法是走3步。

My question is, why we are returning 1 when n=0??我的问题是,为什么我们在 n=0 时返回 1?

It means, there is only one possible way to reach 1st stair.这意味着,只有一种可能的方式到达第一级楼梯。 You can understand more about it by going through https://medium.com/trick-the-interviwer/the-staircase-problem-9840b11201a5您可以通过https://medium.com/trick-the-interviwer/the-staircase-problem-9840b11201a5了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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