Java recursion -08 days study notes

Recursion

  • Method A calls method B, it is easy for us to understand!

  • Recursion is: A method call uses A method! It is to call yourself

Using recursion, simple programs can be used to solve some complex problems. 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 requires only a small number of programs to describe the multiple repetitive calculations required to solve the problem , Greatly reducing the amount of program code. The ability 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 you don't have a head, you will fall into a cycle of death.

  • Recursive body: when you need to call your own method.
package com.xin.method;

public class Demo06 {
    
    
    //2!=2*1
    //3!=3*2*1
    //5!=%*4*3*2*1 阶乘

    public static void main(String[] args) {
    
    

        System.out.println(f(5));

    }

     //1!=1
    //2 2*f(1)
    //3 2*f(2)
    public static int f(int n){
    
    
        if (n==1){
    
    
            return 1;
        }else{
    
    
            return n*f(n-1);  //调用自己
        }
    }

}

Main ——→f(5)——→f(4)——→f(3)——→f(2)——→f(1)

Pass the value from f(1) to 2——→f(2)——→f(3)——→f(4)——→f(5)——→Main (output)

Recursive summary

Boundary condition boundary

Pre-stage

Return stage n*(n-1)

Java belongs to the stack mechanism, so when the depth is relatively large, it is not suitable for taking up a lot of space and memory.

Applicable to the case where the base is relatively small

Can you do without recursion without recursion

Guess you like

Origin blog.csdn.net/yibai_/article/details/114497780