跳台阶问题
2012-08-25 19:47
183 查看
题目:一个台阶总共有n级,如果一次可以跳1级,也可以跳2级。求总共有多少种跳法,并分析算法的时间复杂度。
答:用一个函数f(n)来表示n级台阶总的跳法。
1、只有1个台阶,则f(1) = 1;
2、有2个台阶,则f(2) = 2;
3、当有n个台阶时,如果第一次跳1级,有f(n-1)种跳法,如果第一次跳2级,有f(n - 2)种跳法,即f(n) = f(n-1) + f(n-2)。
即为Fibonacci序列。
运行界面如下:
答:用一个函数f(n)来表示n级台阶总的跳法。
1、只有1个台阶,则f(1) = 1;
2、有2个台阶,则f(2) = 2;
3、当有n个台阶时,如果第一次跳1级,有f(n-1)种跳法,如果第一次跳2级,有f(n - 2)种跳法,即f(n) = f(n-1) + f(n-2)。
即为Fibonacci序列。
#include "stdafx.h" #include <iostream> using namespace std; //循环 int TotalStep(int n) { if (n <= 0) { return 0; } else if (1 == n || 2 == n) { return n; } int first = 1; int second = 2; int total = 0; for (int i = 3; i <= n; i++) { total = first + second; first = second; second = total; } return total; } //递归 int RecurTotalStep(int n) { if (n <= 0) { return 0; } else if (n == 1 || n == 2) { return n; } else { return RecurTotalStep(n - 1) + RecurTotalStep(n - 2); } } int _tmain(int argc, _TCHAR* argv[]) { cout<<TotalStep(20)<<endl; cout<<RecurTotalStep(20)<<endl; return 0; }
运行界面如下:
相关文章推荐
- (2)斐波那契数列及其应用跳台阶问题
- 跳台阶问题-----递归算法
- 微软算法100题27 跳台阶问题
- Solution 27:跳台阶问题
- 递归的logN的优化(菲波那契数列,青蛙上台阶问题,母牛问题)!!!!
- 台阶问题
- Python实现N阶台阶的走法问题
- 跳台阶问题--斐波那契数列
- 跳台阶问题的变种
- 【剑指offer】跳台阶问题
- 27.跳台阶问题
- 程序员面试——走台阶问题
- 青蛙跳台阶问题
- luogu1192 台阶问题
- 台阶问题
- 跳台阶问题(Fabonacci问题)
- 跳台阶问题
- 爬楼梯问题,一共有n阶台阶,每次你可以走1或者2个台阶,到达顶端一共有多少种不同的走法?
- 全排列,跳台阶,奇偶排序,第一个只出现一次等问题
- 斐波那契额数列及青蛙跳台阶问题