recursion

Recursion means calling itself, called recursive call

Steps to solve recursion problem:

1. Suppose the recursive function has been written

2. Find the recurrence relation

3. Convert the structure of the recurrence relation to the recursive body

4. Add critical conditions to the recursive body

Example 1: Find the factorial

function fn(n) {
    if(n===1) {
        return 1;
    }
    return n*fn(n-1);
}
console.log(fn(3));

Example 2: A frog can jump up 1 steps at a time, or 2 steps at a time. Find how many ways the frog can jump up a n-level stair.

Idea: Suppose you jump to level 1 for the first time, then there are f(n-1) kinds of jumping methods, and the first time you jump to level 2, then there are f(n-2) jumping methods. So there are f(n-1)+f(n-2) kinds in total.

function jumpFloor(number){
    if(number<=2){
        return number;
    }
    return jumpFloor(number-1)+jumpFloor(number-2);
}

Example 3: Rabbits give birth to rabbits--a pair of rabbits is born every month from the 3rd month after birth, and a pair of rabbits is born every month after the little rabbit grows to the third month. If the rabbits don't die, ask each What is the number of rabbit pairs in months?

Ideas: 1,1,2,3,5...Analyze the data to get f(n)=f(n-1)+f(n-2)

function born(n) {
    if(n < 3) {
        return n;
    }
    return born(n-2)+born(n-1)
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324608046&siteId=291194637