Recursion (Factorial, Tower of Hanoi problem)

Factorial (introduced)

Give a simple factorial case
n! = n (n-1) (n-2) 2 1
n! = n * (n-1)!
(n-1)! = (n-1)
(n-2) !

2! = 2 * 1! = 2
1! = 1

Calculating factorial can particularly reflect the idea of ​​recursion

  • 1. Decompose a large and complex problem into several similar sub-problems
    • 2. Sub-problems can continue to be decomposed
    • 3. The final sub-problem is decomposed very small, so small that you can know the answer casually
    • 4,Finally, combining the solutions of all the sub-problems is the solution to the complex problem

How to write a recursion

Write recursion, don’t think about anything else,First think about when to stop, first think about the recursive exit
Then write recursive exit

Pros and cons

Advantages of recursion: it can break down big problems into small ones, which is very conducive to thinking, and the code is often not complicated.
But recursion is dangerous, takes up space, and is low in efficiency
. Don't use it under normal circumstances.

java code implementation

    //使用递归求解阶乘
    public static int factorial(int n) {
    
    
        if (n == 1) {
    
    
            return 1;
        } else {
    
    
            return n * factorial(n - 1);
        }
    }

The Tower of Hanoi Problem (Classic)

rule

Simply put: there are three towers 1, 2, 3,There are N (N>1) perforated discs on tower 1, the big disc is on the bottom, and the small disc is on the top
It is required to move all discs to Tower 3 according to the following rules:

  • ​ 1,Only one disc can be moved at a time
  • ​ 2,The big market must be below the small market

Ideas

In fact, no matter how many n is equal to, a rule can be summed up

Part 1: Move all the plates except the largest plate to the auxiliary tower 2.
Part 2 : Move the big plate from tower 1 to tower 3.
Part 3 : use tower 1 to assist and put it in tower 2. All plates except the largest plate, move to tower 3

achieve


Fibonacci sequence

rule

Enter a data n, calculate the nth value of Fibonacci sequence (Fibonacci)

1 1 2 3 5 8 13 21 34 55

Law: A number is equal to the sum of the first two numbers.
Requirements: Calculate the nth value of the Fibonacci sequence (Fibonacci) and print out the entire sequence

achieve

Guess you like

Origin blog.csdn.net/AC_872767407/article/details/113391313