What is recursion?

Recursive: delivery + return operations

The process of resolving big problems into small ones. The reason why it can be resolved is because the handling of major issues is the same as that of minor issues.
1. To call yourself;
2. To have a condition that tends to end.

Here is a brief introduction with an example of finding factorial:

public class recursion {
    
    
    public static int fac(int n) {
    
    
        if(n == 1){
    
    
            return 1; //终止条件
        }
        return n * fac(n-1); //调用自身
    }
    public static void main(String[] args) {
    
    
        System.out.println(fac(5));
    }
}
// 运行结果: 120

The following is the recursive process: (the first dimension)

Insert picture description here
The second dimension: call a method, you need to open up the memory on the stack
stack is advanced out after the
first call fac (5), progressively call fac (4) ...... until the termination conditions
push the process is the delivery process

Insert picture description here
As long as the terminating conditions return, the end of the function, and gradually return value fac (n) of
the stack is the process of normalization process
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/108824154