How to understand function recursion precisely?

前端 未结 4 1085
不知归路
不知归路 2020-12-03 13:08

I am currently programming some divide-conquer algorithms, where function recursions are used everywhere, but I have very vague idea or no idea how exactly it works, and tha

4条回答
  •  醉梦人生
    2020-12-03 13:40

    You are right, I also find recursive functions difficult to understand. Here is what i do, if i see a recursive function: run all the code step by step in your mind. This advice may seem trivial, but most of the time it works for me. Let's look at your code: You call Recursion() function with parameter 3. It prints n and n>0 that's why it calls Recursion(2) (note that we didn't return from the Recursion(3) call we are still in it and now we are also in Recursion(2). The same is for recursion(1) and 0. Now n>0 conditional is false. It prints 0. and we return from recursion(0) We print 1 and return from recursion(1) and it goes on the recursion(3)

    Recursion(3)
        Recursion(2)
            Recursion(1)
                Recursion(0)  
                return from Recursion(0)
            return from Recursion(1)
        return from Recursion(2)
    return from Recursion(3)
    

提交回复
热议问题