跳台阶问题(Fabonacci问题)

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
 
 1 class Solution {
 2 public:
 3     int jumpFloor(int number) {
 4         if(number==1)
 5             return 1;
 6         if(number==2)
 7             return 2;
 8         long long temp2 = 1;
 9         long long temp1 = 2;
10         long long temp =0;
11         for(int i=3;i<=number;i++){
12             temp = temp1+temp2;
13             temp2 = temp1;
14             temp1 = temp;
15         }
16         return temp;
17     }
18 };

改变题目:

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
用数学归纳法,可得f(n)=2^(n-1)
1 class Solution {
2 public:
3     int jumpFloorII(int number) {
4         int result = 1;
5         for(int i=1;i<number;i++)
6             result *=2;
7         return result;
8     }
9 };
转载请注明出处: C++博客园:godfrey_88 http://www.cnblogs.com/gaobaoru-articles/
原文地址:https://www.cnblogs.com/gaobaoru-articles/p/5238605.html