# 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 problems**At 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

- Various mathematical problems, such as: 8 queen problem, Hanoi Tower, factorial problem, maze problem, ball and basket problem（
`google`

Programming contest) - Recursion is also used in various algorithms, such as fast sorting, merge sorting, binary search, divide and conquer algorithm, etc
- The problem to be solved by stack is more concise

# Important rules of recursion

- When a method is executed, a new protected independent space (stack space) is created
- Local variables of methods are independent and do not affect each other, such as
`n`

variable - If a reference type variable (such as an array) is used in a method, the data of that reference type will be shared
- Recursion must approach the condition of exit recursion, otherwise it will be infinite recursion and appear
`StackOverflowError`

Dead turtle:) - 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)

This work adoptsCC agreementReprint must indicate the author and the link of this article