[Java method learning] recursion

Recursion

Recursion is: method A calls method A! Just call yourself, similar to the following:

n*f(n-1)

Using recursion, simple programs can be used to solve some complex problems. It usually transforms a large and complex problem layer by layer into a smaller problem similar to the original problem to solve. The recursive strategy requires only a small number of programs to describe the multiple repetitive calculations required in the process of solving the problem. Reduce the amount of program code. The power of recursion lies in the use of limited statements to define an infinite set of objects.

The recursive structure consists of two parts:

Recursive header : when not to call its own method. If there is no head, it will fall into an endless loop.

Recursive body : When do you need to call your own method.

public static void main(String[] args) {
    
    
    System.out.println(f(4));//输出结果为4的阶层24即 4!=4*3*2*1=24
}
//求解的是n的阶层
public static int f(int n){
    
    
    if (n==1){
    
    
        return 1;
    }else {
    
    
        return n*f(n-1);
    }
}

Guess you like

Origin blog.csdn.net/weixin_44302662/article/details/114681944