Data structures and algorithms of recursive

Data structures and algorithms of recursive


table of Contents

  1. The concept of recursion
  2. Recursive call mechanism
  3. Recursive small code demonstrates
  4. Recursion can solve any kind of problem
  5. Recursive important rules you need to follow

1. The concept of recursion

Simply put, is the recursive method calls itself, passing different variables on each call, recursion can help programmers to solve complex problems, while allowing code becomes simple.


2. recursive call mechanism

Use illustrates our recursive call mechanism
Here Insert Picture Description


3. Small recursive code demonstrates

package com.recursion;

public class recursionTest {
    public static void main(String[] args) {

        test(4);
        System.out.println("======================");
        int res = factorial(3);
        System.out.println("res=" + res);
    }

    //打印问题
    public static void test(int n) {
        if (n > 2) {
            test(n - 1);
        }
        System.out.println("n=" + n);
    }

    //阶乘问题
    public static int factorial(int n) {
        if (n == 1) {
            return 1;
        } else {
            return factorial(n - 1) * n;
        }
    }
}

Compile the results:
Here Insert Picture Description


4. recursion can solve any problem

  1. A variety of mathematical problems such as: 8 queens problem, the Towers of Hanoi problem, factorial problem, maze, ball and basket (google Programming Contest)
  2. A variety of algorithm will use recursion, such as fast row, merge sort, binary search, divide and conquer algorithm,
  3. The problem with a stack> The return code is relatively simple

5. recursive important rules you need to follow

  1. The implementation of a method, it creates a new protected independent space (stack space)
  2. The method is independent of local variables do not affect each other, such as the variable n
  3. If the variable is a reference type (such as arrays) used in the method, it will be shared by the type of data references,
  4. Recursive approach to the conditions must withdraw recursion , or is infinite recursion, there StackOverflowError, a dead turtle :)
  5. When a method is finished, or encountered return, will return, observe who call, who will return the results to the same time when the method completes or returns, which also finished

Guess you like

Origin blog.csdn.net/weixin_41910694/article/details/92843375