Time：2021-4-16

# recursion

## Maze problem (backtracking) ## concept

In a nutshell: recursion means that a method calls itself, passing in different variables each time,Recursion helps programmers solve complex problemsAt the same time, make the code concise

## Case recursive call mechanism

### Printing problems

``````public static void test(int n){
if(n>2){
test(n-1);
}
System.out.println("n="+n);
}``````  Recursive call rule:

### Factorial problem

``//Factorial problem``

### Fibonacci sequence

This can also be realized by recursion

Classic cases

# What kind of problem is recursion used to solve

1. Various mathematical problems, such as: 8 queen problem, Hanoi Tower, factorial problem, maze problem, ball and basket problem（`google`Programming contest)
2. Recursion is also used in various algorithms, such as fast sorting, merge sorting, binary search, divide and conquer algorithm, etc
3. The problem to be solved by stack is more concise

# Important rules of recursion

1. When a method is executed, a new protected independent space (stack space) is created
2. Local variables of methods are independent and do not affect each other, such as`n`variable
3. If a reference type variable (such as an array) is used in a method, the data of that reference type will be shared
4. Recursion must approach the condition of exit recursion, otherwise it will be infinite recursion and appear`StackOverflowError`Dead turtle:)
5. When a method is executed, or when`return`, will return. Whoever calls will return the result to whom. At the same time, when the method is executed or returned, the method will be executed.

# case

## The ball and basket problem

You have several of the same balls and you want to put them in several baskets. Each basket has the same capacity. Give the baskets of int type, which represents the number of baskets. The capacity of int type is given, which represents the maximum capacity of each basket. The number of balls in the basket is represented by balls of int type. The return value is the number of ways to group the balls into the basket. If it cannot be completely stored in the basket and cannot be divided, return 0. The baskets are different, all the balls are the same. So if you put two balls in two baskets, you can do it in three ways, namely (0, 2), (1, 1), or (2, 0)