How does the recursion here work?

后端 未结 9 1172
悲&欢浪女
悲&欢浪女 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.

提交回复
热议问题