一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
题目刚开始我想到的是二叉树。左1右2,后来想想非常的麻烦,然后我找寻了一下规律。
f(n) = f(n - 1)+f(n - 2).采用递归或者迭代比较方便,类似斐波那契数列。
class Solution {
public:
int jumpFloor(int number) {
int total = 0;
int f1 = 1;
int f2 = 2;
if(number == 0)
return 0;
if(number == 1)
return 1;
if(number == 2)
return 2;
for(int i = 2;i < number;i++)
{
total =f1+f2;
f1 = f2;
f2 = total;
}
return total;
}
};