1. Title Description
A frog can jump on a Class 1 level, you can also hop on level 2. The frog jumped seeking a total of n grade level how many jumps (the order of different calculation different results).
2. The ideas and methods
Each jump frog only two options: Level 1 jump reaches the n-th stage ladder step, this time in the first-stage small frogs step n-1; jump or stage 2 reaches the n-th stage ladder step, this time a small frog It is n-2-step . Thus, n jump-step process always depends on the total number n-1 pre-step jump method F (n-1) n-2 and the front-step jump method Total f (n-2). Because only two possibilities, therefore, f (n) = f ( n-1) + f (n-2);
Recurrence formula f (n) = f (n-1) + f (n-2): very familiar, is the Fibonacci Summation verify, there is one kind of grade 1 frog jumps, there are two kinds of level 2 jump method, there are three three jump method, there are five four jumps.
3. C ++ core code
3.1 Recursive (inefficient, time complexity O (n- 2 ))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int jumpFloor(int number) { 4 if(number==1) 5 return 1; 6 else if(number==2) 7 return 2; 8 else{ 9 return jumpFloor(number-1)+jumpFloor(number-2); 10 } 11 } 12 };
3.2 nonrecursive (time complexity of O (n))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int jumpFloor(int number) { 4 if (number < 0) 5 { 6 return 0; 7 } 8 if (number == 0 || number == 1 || number == 2) 9 { 10 return number; 11 } 12 int f1 = 1; 13 int f2 = 2; 14 int result = 0; 15 for (int i = 3; i <= number; i++) 16 { 17 result = f1 + f2; 18 f1 = f2; 19 f2 = result; 20 } 21 return result; 22 } 23 };
Reference material
https://blog.csdn.net/qq_33022911/article/details/83536283