How does the recursion here work?

后端 未结 9 1135
悲&欢浪女
悲&欢浪女 2021-01-04 12:18

Code 1:

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


        
相关标签:
9条回答
  • 2021-01-04 12:59

    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.

    Consider these text instructions:

    To sort numbered blocks:

    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.

    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.

    0 讨论(0)
  • 2021-01-04 13:00

    Understanding recursion requires also knowing how the call stack works i.e. how functions call each other.
    If the function didn't have the condition to stop if n==0 or n==1, then the function would call itself recursively forever. It works because eventually, the function is going to petter out and return 1. at that point, the return fibonacci (n-1) + fibonacci (n-2) will also return with a value, and the call stack gets cleaned up really quickly.

    0 讨论(0)
  • 2021-01-04 13:02

    The trick is that the first call to fibonacci() doesn't return until its calls to fibonacci() have returned.

    You end up with call after call to fibonacci() on the stack, none of which return, until you get to the base case of n == 0 || n == 1. At this point the (potentially huge) stack of fibonacci() calls starts to unwind back towards the first call.

    Once you get your mind around it, it's kind of beautiful, until your stack overflows.

    0 讨论(0)
提交回复
热议问题