Recursion, is that simple

Recursion

What is recursion?

Wikipedia gives the following definition:

Program that calls itself recursively programming technique called recursive algorithm is widely used as a programming language.

Slightly above the official statement. In short, that calls itself recursively, but it is this call certain conditions, such as:

  • Sub-problems to be the original problem is the same thing, and easier.
  • The number of calls can not own too much, otherwise it will cause the program stack overflow.
  • You must set boundaries recursive, that is recursive end condition, otherwise it will be a recursive infinite loop until the program stack overflow.

And the difference between the recursive loop

  • Recursion

Advantages: code is simple and clear (you need to understand the algorithm, otherwise it will be more halo) Cons: number of calls control is not good, likely to cause a stack overflow. In addition, each time it passes parameters are equivalent to push each returned result are the equivalent of a stack, the impact of the implementation process is very efficient.

  • cycle

Advantages: simple logic, speed Disadvantages: can not solve all the problems, some issues must be implemented with recursion. For example, if the famous Chinese Tower problems, if anyone can write out my clothes in other ways.

Recursive usage scenarios

About usage scenarios, I summed up the word: to achieve a very small number of calls and nausea when using loop, you can try using recursion.

Several examples of recursive

  1. Int type array calculates the sum
public class Main {

    private static int sum(int[] arr, int z) {

        if (z == arr.length) {
            return 0;
        }

        int x = sum(arr, z + 1);

        int res = arr[z] + x;

        return res;
    }


    public static void main(String[] args) {
        int arr[] = {1, 2};
        sum(arr, 0);
    }
}
复制代码

The simplest example of this, of course, the problem here is for the convenience of explanation, in fact, is the best use to achieve cycle. Purpose is to calculate the sum of the elements of the array arr, see input parameters, we can guess the result is 3. Now I say look at this type of program tips.

First of all, we need to find a recursive border program, which is a recursive end condition (not accurate to say, look at the specific code to achieve, sometimes recursive border is indeed recursive end condition, returns the final result, but sometimes it is a recursive last conditions layer returns result, the following procedure for example).

  • When z = 2, this layer recursively returns 0, i.e. x = 0, z = returned to this layer 1 is recursive.
  • In this case, res = arr [1] + 0, i.e. return res = 2 x = 2 to this layer to z = 0 of the recursion.
  • In this case, res = arr [0] + 2 = 3 Thus, the end of the recursion, the result returned to the caller.

Did not understand, please copy the code debug step by step operation. Anyway, I was beginning to see the halo around.

  1. Calculate the sum of 1 to 100
public class Main {

    static int i = 1;

    public static void show(int sum) {
        sum = sum + i; //业务代码1
        //递归头
        if (i == 10) {
            System.out.println(sum);
            return;
        }
        i++;   //业务代码2
        show(sum); //递归体
    }

    public static void main(String[] args) {
        int sum = 0;
        show(sum);
    }
}
复制代码

Written above recursive border, belongs I said above, it is the end of recursive conditions. Its return is the result of the recursive end result, rather than the result of a layer.

  1. Fibonacci number
public class Main {
 
    public static int f(int n) throws Exception {
        if(n==0){
           throw new Exception("参数错误!");
        }
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return f(n-1)+f(n-2); //自己调用自己
        }
 }
 
 
    public static void main(String[] args) throws Exception {
        for (int i = 1; i <=10; i++) {
            System.out.print(f(i)+" ");
        }
    }  
}
复制代码
  1. Calculate folder size

Since the length of the File class () (return type long type) method can only file size statistics, there is no direct method of statistical size of a folder, the method requires the use of a recursive traversal of all the files, and accumulate, ultimately calculate the file folder size.

public class Main {

    public static void main(String[] args) {
        File dir = getDir();
        System.out.println(getFileLength(dir));
        System.out.println("统计完成!");
    }
    
    public static File getDir() {
        //1,创建键盘录入对象
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个文件夹路径:");
        //2,定义一个无限循环
        while(true) {
            //3,将键盘录入的结果存储并封装成File对象
            String line = sc.nextLine();
            File dir = new File(line);
            //4,对File对象判断
            if(!dir.exists()) {
                System.out.println("您录入的文件夹路径不存在,请重新录入:");
            }else if(dir.isFile()) {
                System.out.println("您录入的是文件路径,请重新录入:");
            }else {
                //5,将文件夹路径对象返回
                return dir;
            }
        }        
    }

    public static long getFileLength(File dir) {
        //1,定义一个求和变量
        long len = 0;
        //2,获取该文件夹下所有的文件和文件夹listFiles();
        File[] subFiles = dir.listFiles();
        //3,遍历数组
        if(subFiles != null) {
            for (File subFile : subFiles) {
                //4,判断是文件就计算大小并累加
                if(subFile.isFile()) {
                    len = len + subFile.length();
                    //5,判断是文件夹,递归调用
                }else {
                    len = len + getFileLength(subFile);
                }
            }
        }
        return len;
    }
}
复制代码

Summary: This is the definition of recursive introduction, the difference with the circulation as well as its usage scenarios, and finally provides several code examples for everyone to study, read, please copy the code, debug step by step operation to understand.

Reference Links: www.jianshu.com/p/edfc4e35f...

Recommended reading:

1, java | what is a dynamic agency

2, SpringBoot | start principle

3, SpringBoot | automatic configuration principle

A good basket

Guess you like

Origin juejin.im/post/5d482eed518825262a6bc39f