Understanding how recursive functions work

后端 未结 18 735
野性不改
野性不改 2020-11-22 07:08

As the title explains I have a very fundamental programming question which I have just not been able to grok yet. Filtering out all of the (extremely clever) \"In order to

18条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 07:44

    To understand recursion you must think of the problem in a different way. Instead of a large logical sequence of steps that makes sense as a whole you instead take a large problem and break up into smaller problems and solve those, once you have an answer for the sub problems you combine the results of the sub problems to make the solution to the bigger problem. Think of you and your friends needing to count the number of marbles in a huge bucket. You do each take a smaller bucket and go count those individually and when you are done you add the totals together.. Well now if each of you find some friend and split the buckets further, then you just need to wait for these other friends to figure out their totals, bring it back to each of you, you add it up. And so on. The special case is when you only get 1 marble to count then you just return it back and say 1. let the other people above you do the adding you are done.

    You must remember every time the function calls itself recursively it creates a new context with a subset of the problem, once that part is resolved it gets returned so that the previous iteration can complete.

    Let me show you the steps:

    sumInts(a: 2, b: 5) will return: 2 + sumInts(a: 3, b: 5)
    sumInts(a: 3, b: 5) will return: 3 + sumInts(a: 4, b: 5)
    sumInts(a: 4, b: 5) will return: 4 + sumInts(a: 5, b: 5)
    sumInts(a: 5, b: 5) will return: 5 + sumInts(a: 6, b: 5)
    sumInts(a: 6, b: 5) will return: 0
    

    once sumInts(a: 6, b: 5) has executed, the results can be computed so going back up the chain with the results you get:

     sumInts(a: 6, b: 5) = 0
     sumInts(a: 5, b: 5) = 5 + 0 = 5
     sumInts(a: 4, b: 5) = 4 + 5 = 9
     sumInts(a: 3, b: 5) = 3 + 9 = 12
     sumInts(a: 2, b: 5) = 2 + 12 = 14.
    

    Another way to represent the structure of the recursion:

     sumInts(a: 2, b: 5) = 2 + sumInts(a: 3, b: 5)
     sumInts(a: 2, b: 5) = 2 + 3 + sumInts(a: 4, b: 5)  
     sumInts(a: 2, b: 5) = 2 + 3 + 4 + sumInts(a: 5, b: 5)  
     sumInts(a: 2, b: 5) = 2 + 3 + 4 + 5 + sumInts(a: 6, b: 5)
     sumInts(a: 2, b: 5) = 2 + 3 + 4 + 5 + 0
     sumInts(a: 2, b: 5) = 14 
    

提交回复
热议问题