超级楼梯 递推

超级楼梯

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 42   Accepted Submission(s) : 34

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

Problem Description

有一楼梯共M级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第M级,共有多少种走法?

Input

输入数据首先包含一个整数N,表示测试实例的个数,然后是N行数据,每行包含一个整数M(1<=M<=40),表示楼梯的级数。

Output

对于每个测试实例,请输出不同走法的数量

Sample Input

2
2
3

Sample Output

1
2
因为每次只能走一级或者两级,所以可以知道有两种走法,就是前面走n-1步的走法再走一步和前面n-2步的走法再走2步
所以可以得到递推式f(n)=f(n-1)+f(n-2)
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 long long a[50];
 4 int main()
 5 {
 6     int n;
 7     a[1]=1,a[2]=1,a[3]=2;
 8     for(int i=4;i<=40;i++)
 9     {
10         a[i]=a[i-1]+a[i-2];
11     }
12     while(~scanf("%d",&n))
13     {
14         
15         for(int i=0;i<n;i++)
16         {
17             int m;
18             cin>>m;
19             printf("%lld\n",a[m]);
20         }
21     }
22     return 0;
23 }

猜你喜欢

转载自www.cnblogs.com/fqfzs/p/9763741.html