Classic algorithm-recursion (bunny case)

Preface

Algorithm is a necessary knowledge for programmers. From now on, come and learn algorithms with me!

1. What is recursion

Recursion is a way to realize the concept of recursion in mathematics in computer programming. Simply put, it is a programming technique in which a program calls itself.

A process or function has a method of directly or indirectly calling itself in its definition or description. It usually converts a large and complex problem into a smaller problem similar to the original problem to solve. The recursive strategy only A small amount of programs can describe the multiple repetitive calculations required in the process of solving the problem, which greatly reduces the amount of program code

Two, use cases

There is a pair of rabbits. From the third month after birth, a pair of rabbits will be born every month, and the little rabbit will give birth to a pair of rabbits every month after the third month. If the rabbits are not dead, ask the rabbits every month What is the total?

First analyze the question:

The number of rabbits in the first few months is: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144. From the data, we can find that from the third month, the rabbits of each month The number is the sum of the number of rabbits in the previous two months

At this time, a recursive condition is satisfied, and we can use recursion in the program to implement such a calculation:

int GetNub(int n)   
{
    
    
    int nub;
    if(n==1||n==2) nub=2;   
    else nub = GetNub(n-1)+GetNub(n-2);   //在程序中调用自身把问题简化
    return nub;
}

Third, how to cultivate recursive thinking

Recursive thinking is often accompanied bytimelineDevelopment, and there are oftenCertain connectionIf you encounter such a situation, you can consider enumerating the previous data and make a certain rule summary

Guess you like

Origin blog.csdn.net/xinzhilinger/article/details/109230987