A step has a total of n, if you can jump 1 levels at a time, you can also jump 2 levels, the total number of total hop method, and analyze the algorithm time complexity

Source: Internet
Author: User
Package ms100;/** * A step with a total of n-level, if you can jump 1 levels, you can jump 2 levels, the total number of total hop method, and analyze the algorithm time complexity * Note: This problem has recently appeared, including MicroStrategy More attention to the algorithm of the company has selected a problem as a face test or pen test. First of all, we consider the simplest case: if there is only 1 steps, that obviously there is only one jump method, if there are 2 steps, there are two ways to jump: One is divided into two jumps, each jumping 1 levels, and the other is to jump 2 level. Now let's talk about the general situation: we think of the N-Step jumping method as a function of N, which is recorded as f (n). When N>2, the first jump when there are two different choices: first, only jump 1, when the number of hops is equal to the rest of the n-1 steps of the number of jumps, that is f (n-1); Another option is the first jump 2, at this time the number of hops is equal to the rest of the n-2 step of the number of jumps, That is f (n-2). So the total number of different hops for n-Steps is f (n) = f (n-1) + f (n-2). We summarize the above analysis with a formula as follows:       /  1  (n=1) f (n) =  2  (n=2)       \  F (n-1) + (f-2)  (n>2) */public class ms_27 {private int jumpstep (int n) {if (n<0) return 0;if (n==1| | n==2) return N;return jumpstep (n-1) + jumpstep (n-2);} public static void Main (string[] args) {ms_27 ms27 = new ms_27 (); System.out.println (Ms27.jumpstep (2));}}

A step has a total of n, if you can jump 1 levels at a time, you can also jump 2 levels, the total number of total hop method, and analyze the algorithm time complexity

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.