- 题目描述:
-
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
- 输入:
-
输入可能包含多个测试样例,对于每个测试案例,
输入包括一个整数n(1<=n<=70)。
- 输出:
-
对应每个测试案例,
输出该青蛙跳上一个n级的台阶总共有多少种跳法。
样例输入:
5
样例输出:
8
【解题思路】题目从正面突破很难,我们可以换个角度思考,跳上第n个台阶有几种跳法?有两种跳法:从第n-1台阶跳和从第n-2台阶跳。从而,我们自然而然的得到第n个台阶的跳法等于第n-1台阶的跳法+第n-2台阶的跳法。这与斐波拉契数列是不是很像,这样我们很快就能想到万能的递归解法。递归的终止条件是当n==0和n==1时我们能很快知道有几种跳法。
AC code:
#include <cstdio> #include <vector> using namespace std; int main() { int n,siz; vector<long> vec; vec.reserve(72); vec.push_back(1); vec.push_back(1); while(scanf("%d",&n)!=EOF) { if(n>=vec.size()) { siz=vec.size(); for(int i=siz;i<=n;++i) vec.push_back(vec[i-1]+vec[i-2]); } printf("%ld ",vec[n]); } return 0; } /************************************************************** Problem: 1388 User: huo_yao Language: C++ Result: Accepted Time:0 ms Memory:1052 kb ****************************************************************/
题目链接:http://ac.jobdu.com/problem.php?pid=1388