I. Recursion

1. Basic concepts

In simple terms, recursion means that the method calls itself, passing in a different variable each time. Recursion helps programmers solve complex problems while keeping code simple

2. Call mechanism

Use an example to illustrate the recursive invocation mechanism

3. Problems solved

  • Various math problems: 8 queens, Hannott’s Tower, factorial problem, maze problem, ball and basket problem
  • Recursion is also used in various algorithms, such as quicksort, binary search, divide-and-conquer, etc
  • Problems that need to be solved with stacks

4. Rules to follow

  • When a method is executed, a new protected independent space (stack space) is created
  • The local variables of a method are independent and do not affect each other, such as the n variable; If a method uses a variable of a reference type (such as an array), the data of that reference type is shared.
  • The recursion must approach the condition for quitting recursion, otherwise it will be infinite recursion, causing stack overflow
  • When a method completes execution, it returns (if there is a return value, just as the result of execution is returned to the caller)

The application of recursion