[Sword Point offer] abnormal jumping steps

Source: Internet
Author: User

Title Description

A frog can jump up to 1 steps at a time, or jump up to level 2 ... It can also jump on n levels. To ask the frog to jump on an n-level stair total number of hops

Enter a description

Number of steps

Output description

Jump Method Number

Problem analysis
    • Set N-order hop number to F (n)

    • When N=1, f (1) = 1

    • When the n=2, divided into the last step 2 and jump 1 order two cases, there is f (2) =f (0) +f (1) =1+1=2

    • When n=3, divided into the last step to jump 3 order, jump 2 order and jump 1 order three cases, there is f (3) =f (0) +f (1) +f (2) =1+1+2=4

    • With f (n) = f (n-1) +f (n-2) +...+f (1) + F (0) established
      At the same time F (n-1) =f (n-2) +...+f (1) + f (0) is established, can be obtained f (n) =2f (n-1) (n>=2)

 

It is obvious that a recursive formula can be derived:

| 1 (n=0)
F (n) = | 1 (n=1)
| 2*f (n-1) (n>=2)

Solution one run time: 35ms occupied memory: 654k

publicclass Solution {    publicintJumpFloorII(int target) {        if(target<=1)  return1;        return2*JumpFloorII(target-1);    }}

Solution two run time: 34ms occupied memory: 654k

publicclass Solution {    publicintJumpFloorII(int target) {   if(target<=1)  return1;        return1<<(target-1);    }}

Another way to think about it: a total of n steps, the last step is bound to jump up, the other n-1 can jump not jump, altogether how many total situation?

2 (n-1)

Here, multiply with the shift, faster in time!

[Sword Point offer] abnormal jumping steps

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.