The programming technique of a program calling itself is called recursion. Recursion is widely used as an algorithm in programming languages. A process or function has a method to directly or indirectly call itself in its definition or description. It usually converts a large and complex problem layer by layer into a smaller problem similar to the original problem to solve. The recursive strategy only requires a small number of programs to describe the multiple repeated calculations required for the problem-solving process, greatly reducing the amount of code in the program. The ability of recursion lies in using finite statements to define an infinite set of objects. Generally speaking, recursion requires boundary conditions, recursive advance segments, and recursive return segments. When the boundary condition is not satisfied, proceed recursively; when the boundary condition is satisfied, return recursively. ―This is what Baidu Encyclopedia said.
In fact, to put it bluntly, it is the operation performed by the recursive method itself calling itself. Let me give you an example to illustrate this example, which is a very famous Fibonacci sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368…
It can be seen that the third number is obtained by adding the first two numbers.
This is what it means if you use a normal loop:
public class FeiBo{ public static void main(String[] args) { int num1=0; int num2=1; int numn=1; int n=10; for (int i = 3; i <=n; i++) { numn=num1+num2; num1=num2; num2=numn; } System.err.println(n+" result is: "+numn); }}The operation result is:
The result of 10 numbers is: 34
This is to use normal loop method for operation, if you use recursion, it is like this:
public static int Recursion(int n){ if(n==1){ return 0; } if(n==2){ return 1; } return Recursion(n-1)+Recursion(n-2); }Recursion requires an end condition, and in the case recursion does not need to continue calling, ending recursion. The end condition of the above case is that when n=1 or 2, it returns 0 or 1, instead of continuing to call the recursive method itself.
The two main conditions for recursion are to call yourself and end the recursion.
Because recursion is called by oneself, it wastes a lot of resources, the running time is much longer than the loop, the running time is slower, and the efficiency is low.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.