[The Road to becoming a King of Java] Part 5: Java SE (method recursion)

a928ad769e124c43ab65cc472fed8870.gif

 

content

 

The concept of recursion

1. What is recursion?

2. Recursive explanation 

The use of recursion 

Example: Find the factorial of n recursively

Drawing analysis:

Example: find the sum of n

Example: Recursive implementation prints each digit in order 

Implementation code:

Example: Find the nth Fibonacci number 

Summarize: 

I am with you.


 

The concept of recursion

1. What is recursion?

Recursion is the process of a method calling a method by itself.

There are two prerequisites for using recursion:

1. There is an approach and termination condition.

2. Invoke yourself by yourself.

How to implement recursion?

The most important way is: to achieve recursion, you need to derive a recursive formula.

The recursive way of thinking: thinking laterally, thinking in terms of recursive formulas.

Code execution: vertical execution.

2. Recursive explanation 

First look at the following code:

public class TestDemo {
    public static void func(){
        
        func();   //自己调用自己本身
    }


    public static void main(String[] args) {
        func();

    }
}

The above code is a simple recursion.

Let's take a look at the result of running this code,

Drawing explanation:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAS-WqvuKAjQ==,size_20,color_FFFFFF,t_70,g_se,x_16

 For the recursion in the above figure, there is no condition that tends to terminate at all, so the function will recurs endlessly. Every recursion has to open up memory on the stack, and always open up memory on the stack, there will always be a stack overflow.

Old irons should remember: once you write a problem with the recursion, if the boundary is not right, you will definitely report one 7ae60fddda4c4c9183eef750dc310410.png. If you report this error, then your termination condition must be wrong, or you have not written the termination condition. In the process of recursion, the depth is too large, and eventually the stack overflows.

 

To make the above code correct, we need to add a termination condition to it.

The correct code is as follows:

public class TestDemo {
    public static void func(int n){
        if(n == 1) return;
        func(n -1);
    }


    public static void main(String[] args) {
        func(3);

    }
}

The following will give you a more in-depth understanding of recursion through simple examples.

The use of recursion 

Example: Find the factorial of n recursively

Drawing analysis:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAS-WqvuKAjQ==,size_20,color_FFFFFF,t_70,g_se,x_16

Implementation code:

public class TestDemo {
    public static int fac(int n){
        if(n == 1) {
            return 1;
        }
        int tmp = n * fac(n - 1);
        return tmp;
    }
    public static void main(String[] args) {
        System.out.println(fac(5));

    }
}

Code drawing explanation:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAS-WqvuKAjQ==,size_20,color_FFFFFF,t_70,g_se,x_16

Example: find the sum of n

Drawing analysis :

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAS-WqvuKAjQ==,size_20,color_FFFFFF,t_70,g_se,x_16

 Implementation code:

第一种写法:
public class TestDemo {
    public static int sumAdd(int n){
        if(n == 1) {
            return 1;
        }
        int tmp = n + sumAdd(n - 1);
        return tmp;
    }
    public static void main(String[] args) {
        System.out.println(sumAdd(3));

    }
}

第二种写法:
public class TestDemo {
    public static int sumAdd(int n){
        if(n == 1) {
            return 1;
        }
       
        return n + sumAdd(n -1);
    }
    public static void main(String[] args) {
        System.out.println(sumAdd(3));

    }
}

Example: Recursive implementation prints each digit in order 

Drawing analysis:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAS-WqvuKAjQ==,size_20,color_FFFFFF,t_70,g_se,x_16

 Implementation code:

public class TestDemo {

    public static void print(int n){
        if(n < 10){
            System.out.print(n+" ");
        }else{
            print(n/10);
            System.out.print(n%10+" ");
        }
    }
    public static void main(String[] args) {
        print(1234);


    }
}

Example: Write a recursive method that takes a non-negative integer and returns the sum of the numbers that make it up. For example: enter 1729, it should return 1+7+2+9

Implementation code:

public class TestDemo {


    public static int sumEveryone(int n){
        if(n < 10){
           return n;
        }else{
            return n%10 + sumEveryone(n/10);
        }
    }

    public static void main(String[] args) {
        System.out.println(sumEveryone(7910));

    }

}

Example: Find the nth Fibonacci number 

Drawing analysis:

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAS-WqvuKAjQ==,size_20,color_FFFFFF,t_70,g_se,x_16

Implementation code:

第一种方法:递归
public class TestDemo {
    public static int fib(int n){
        if(n == 1 || n == 2){
            return 1;
        }else{
            return fib(n-2)+fib(n-1);
        }
    }
    public static void main(String[] args) {
        System.out.println(fib(5));

    }



第二种方法:叫做循环(迭代)实现
    public static int fib2(int n){
        if(n == 1 || n==2){
            return 1;
        }
            int f1 = 1;
            int f2 = 1;
            int f3 = 0;
            for (int i = 3; i < n; i++) {
                f3 = f1+f2;
                f1 = f2;
                f2 = f3;
            }
            return f3;

    }
    public static void main(String[] args) {
        System.out.println(fib2(45));

    }

Summarize: 

This article briefly introduces what recursion is, how to explain recursion, and how to use recursion. Deepen the impression of recursion through simple examples. The above is the content of today. If you have any questions, you can privately message me at any time. I will actively correct any problems in the article. I also hope that everyone can master the knowledge they want faster, let’s work together! ! ! ! !

I am with you . _

23ed9e1109544bcb98ce1bb86bc1f9a0.gif

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/m0_64397675/article/details/123190108