Sword refers to offer—Supplement 1. Jumping the stairs—Analysis and code (Java)

Sword refers to offer-supplement 1. Jump up the stairs-analysis and code [Java]

1. Title

A frog can jump up to 1 step or 2 steps at a time. Find the total number of jumping methods the frog jumps on an n-level step (different order counts as different results).

Two, analysis and code

1. Dynamic programming

(1) Thinking

Dynamic programming basic problem, because you can jump 1 or 2 steps at a time, assuming that the number of steps to jump to the nth step is F(n), then F(n) = F(n-1) + F(n-2) .
The result is the Fibonacci sequence.

(2) Code

public class Solution {
    
    
    public int JumpFloor(int target) {
    
    
        if (target < 3)
            return target;
        int [] ans = new int[target];
        ans[0] = 1;
        ans[1] = 2;
        for (int i = 2; i < target; i++)
            ans[i] = ans[i - 1] + ans[i - 2];
        return ans[target - 1];
    }
}

(3) Results

Running time: 10 ms, occupying 9560 k of memory.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112254750