这里的递归如何工作? [英] How does the recursion here work?

查看:121
本文介绍了这里的递归如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码1:

public static int fibonacci (int n){ 
    if (n == 0 || n == 1) { 
        return 1; 
    } else { 
        return fibonacci (n-1) + fibonacci (n-2); 
    }        
} 

如何使用斐波那契如果你还没有完成它的解释呢?我已经能够理解在其他情况下使用递归:

How can you use fibonacci if you haven't gotten done explaining what it is yet? I've been able to understand using recursion in other cases like this:

代码2:

class two 
{
    public static void two (int n) 
    {
        if (n>0) 
        {
            System.out.println (n) ;
            two (n-1) ;
        }
        else
        {
            return ;
        }
    } 

    public static void main (String[] arg) 
    {
        two (12) ;
    }
}

但在代码2的情况下, n 最终将达到不满足 n> 0 的点,该方法将停止递归调用自身。但是,在代码2的情况下,我不知道如果 n = 1 是2和3的起点,它将如何从1获得5等等。此外,我没有看到返回fibonacci(n-1)+ fibonacci(n-2)这一行将如何工作,因为 fibonacci(n- 2)在某种意义上必须包含 fibonacci(n-1)才能工作,但它还没有。

In the case of code 2, though, n will eventually reach a point at which it doesn't satisfy n>0 and the method will stop calling itself recursively. In the case of code 2, though, I don't see how it would be able to get itself from 1 if n=1 was the starting point to 2 and 3 and 5 and so on. Also, I don't see how the line return fibonacci (n-1) + fibonacci (n-2) would work since fibonacci (n-2) has to contain in some sense fibonacci (n-1) in order to work, but it isn't there yet.

我正在看的这本书说它会起作用。它是如何工作的?

The book I'm looking at says it will work. How does it work?

推荐答案

好吧,把编译器实际对你的代码做的事情放在一边(它太可怕了,但很漂亮) CPU如何实际解释你的代码(同样),这是一个相当简单的解决方案。

Well, putting aside what a compiler actually does to your code (it's horrible, yet beautiful) and what how a CPU actually interprets your code (likewise), there's a fairly simple solution.

请考虑以下文字说明:

要对编号的块进行排序:

To sort numbered blocks:


  1. 选择一个随机块。

  2. 如果是只有阻止,停止。

  3. 将带有较低数字的块
    移动到左侧,将
    移到更高的数字右侧。

  4. 对编号较小的块进行排序。

  5. 对编号较高的块进行排序。

  1. pick a random block.
  2. if it is the only block, stop.
  3. move the blocks with lower numbers to the left side, higher numbers to the right.
  4. sort the lower-numbered blocks.
  5. sort the higher-numbered blocks.

当您收到说明4和5时,系统会要求您重新开始整个过程​​。但是,这不是问题,因为你仍然知道如何启动这个过程,当它最终完成时,你会得到一堆排序的块。你可以用纸条来说明这些说明,它们也不会更难理解。

When you get to instructions 4 and 5, you are being asked to start the whole process over again. However, this isn't a problem, because you still know how to start the process, and when it all works out in the end, you've got a bunch of sorted blocks. You could cover the instructions with slips of paper and they wouldn't be any harder to follow.

这篇关于这里的递归如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆