Sword Finger Offer—Supplement 2. Abnormal Jumping—Analysis and Code (Java)

Sword refers to offer-supplement 2. Abnormal jump-analysis and code [Java]

1. Title

A frog can jump up to 1 step or 2 steps at a time... It can also jump to n steps. Find the total number of jumping methods the frog jumps on an n-level step.

Two, analysis and code

1. Permutation and Combination

(1) Thinking

This question can be solved directly with the idea of ​​permutation and combination in mathematics, because the frog can jump any step at a time, which is equivalent to from the 0th to the nth step. The frogs in the middle n-1 step can choose to jump or not, that is There are 2 ^ (n-1) ways to jump.
In order to improve the operation speed, it can be directly realized by binary shift operation.

(2) Code

public class Solution {
    
    
    public int JumpFloorII(int target) {
    
    
        int ans = 1;
        for (int i = 1; i < target; i++)
            ans <<= 1;
        return ans;
    }
}

(3) Results

Running time: 13 ms, occupying 9332 k of memory.

Three, other

Nothing.

Guess you like

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