https://github.com/PhillipHuang2017/SwordOffer
8. jump stairs
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).
Problem-solving ideas
- To reverse this thinking to think that only due to skip a grade 1 or grade 2 jump, so jump to the first n steps, the last hop only two possibilities, one is a former skip steps 1, another He is a former two steps skip a grade 2, drawn
f(n) = f(n-1) + f(n-2)
, can be seen with the Fibonacci number Fibonacci sequence of method. - Another way to understand is there are two ways the first jump, one is a skip, skip one is 2, 1, then skip if left to stage n-1, if it is, then skip 2 remaining n-2 level, after the first dance through position as a starting point, then jumped on the back of the problem is equivalent to the level and jump on the first n-1 n-2-stairs how many ways can also be come
f(n) = f(n-1) + f(n-2)
. - The law also gradually found by mathematical induction
- And the number of columns as Fibonacci, recursion is very low efficiency, so do recursive
C ++ code
- Common method
class Solution {
public:
int jumpFloor(int number) {
if(number<1){
throw "number must >0";
}
else if(number == 1){
return 1;
}
else if(number == 2){
return 2;
}
else{
int a=1, b=2, temp=0, i=2;
while(i<number){
temp = a + b;
a = b;
b = temp;
i++;
}
return b;
}
}
};
- Sao operation
//其实也是不停地算出下一个值的过程,只不过不容易想到,
//效率和上面的差不多,只不过代码简洁得多
class Solution {
public:
int jumpFloor(int number) {
int a = 1, b = 1;
while(--number){
b += a;
a = b - a;
}
return b;
}
};