The basic concept of recursion: the programming technique of program calling itself is called recursion, and the function itself calls itself.
A function calls its own method directly or indirectly in its definition. It usually converts a large and complex problem into a small problem similar to the original question class, can greatly reduce the amount of code. the ability to recursion lies in the use of limited statements to define an infinite set of objects.
Note the following when using recursion:
1) recursion is to call itself in a process or function;
2) When recursion is used, there must be a clear recursion end condition, called the recursion exit.
Recursion is divided into two phases:
1) recurrence: solve complex problems to solve problems that are simpler than the original ones;
2) regression: When the simplest case is obtained, return gradually and obtain a complex solution in sequence.
Recursion can solve many problems, such as the backpack problem, the tower problem, and so on.
The Fibonacci sequence is: 0, 1, 2, 3, 5...
FIB (0) = 0;
FIB (1) = 1;
FIB (n) = fib (n-1) + fib (n-2 );
Int fib (int n) {If (0 = N) return 0; if (1 = N) return 1; if (n> 1) return fib (n-1) + fib (n-2 );}
The above is a simple recursive call, because recursion causes a series of function calls, and there may be a series of repeated calculations, the running efficiency of recursive algorithms is relatively low.
Iteration: use the original value of the variable to calculate a new value of the variable. If recursion is self-called, iteration is a non-stop call B.
There must be iterations in recursion, but not necessarily in iteration. Most of them can be converted to each other. it can be used for iteration without recursion, recursively calling functions, wasting space, and recursion is too deep and easy, resulting in stack overflow.
// This is recursive int funca (int n) {If (n> 1) return N + funca (n-1); else return 1 ;}// this is an iterative int funcb (int n) {int I, S = 0; for (I = 1; I <n; I ++) S + = I; return s ;}
Difference between Recursion and iteration