[Swipe the question bank] Sword refers to Offer_ programming questions, jumping steps and abnormal jumping steps.

Step up

Title description

A frog can jump up to one step at a time, or up to two steps at a time. Find the total number of jumping methods for the frog to jump on an n-level step (different order counts different results).

Time limit: 1 second Space limit: 32768K Heat index: 475919

Knowledge points of this question:  recursion

 

solution:

Number of steps

0

1

2

3

4

5

6

7

8

9

Jump method

0

1

2

3

5

8

13

21

34

55

Seeing the sequence of this set of numbers, we can see that it is actually a Fibonacci sequence, with the number of steps starting from 3, which is the sum of the first two items.

Solution one: recursive method

function jumpFloor(number)
{
    // write code here
    if(number == 0) return 0;
    if(number == 1) return 1;
    if(number == 2) return 2;
    
    return jumpFloor(number - 1) + jumpFloor(number -2);
}

Time complexity: O(N^2)

Space complexity: O(N)

 

Solution 2: Array Method

Since the time complexity of the recursive method is too high, we might as well try the array method.

function jumpFloor(number)
{
    var array = [];
    array[0] = 0;
    array[1] = 1;
    array[2] = 2;
    
    for(var i = 3; i <= number; i++){
        array[i] = array[i - 1] + array[i - 2];
    }
    return array[number];
}

Time complexity: O(N)

Space complexity: O(N)

Solution two: variable method

The array we defined creates a large space, so we use variable storage to optimize the code.

function jumpFloor(number)
{
    if(number == 0) return 0;
    if(number == 1) return 1;
    if(number == 2) return 2;
    
    var one = 1;
    var two = 2;
    var sum = 0;
    for(var i = 2;i < number; i++){
        sum = two + one;
        one = two;
        two = sum;
    }
    return sum;
}

Time complexity: O(N)

Space complexity: O(1) (four objects are created, which are constants, so they can be ignored)

 

Abnormal jump

Title description

A frog can jump up to one step at a time, or up to two steps at a time. Find the total number of jumping methods for the frog to jump on an n-level step (different order counts different results).

Time limit: 1 second Space limit: 32768K Heat index: 475919

Knowledge points of this question:  recursion

 

 

When solving the problem, the results are as follows

 

Solution one: pow

function jumpFloorII(number)
{
    // write code here
    if(number == 0) return 0;
    
    return Math.pow(2, number-1);
}

 

Solution 2: Shift operation

function jumpFloorII(number)
{
    return 1<<(number-1);
}

Solution three: power operator (**)

function jumpFloorII(number)
{
    return 2 ** (number-1);
}

 

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/100055106