超级楼梯
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 23642 Accepted Submission(s): 12153
Problem Description
有一楼梯共M级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第M级,共有多少种走法?
Input
输入数据首先包含一个整数N,表示测试实例的个数,然后是N行数据,每行包含一个整数M(1<=M<=40),表示楼梯的级数。
Output
对于每个测试实例,请输出不同走法的数量
Sample Input
2
2
3
Sample Output
1
2
Author
lcy
Source
2005实验班短学期考试
Recommend
lcy
水题,递归。
很有意思的一道递归题,用普通的递归会超时,需要改用记忆递归法。记忆递归法,牺牲空间来换取时间,可以采用数组(数组空间浪费大,但是读取速度快)。
code:
1 Problem : 2041 ( 超级楼梯 ) Judge Status : Accepted
2 RunId : 8925185 Language : G++ Author : freecode
3 Code Render Status : Rendered By HDOJ G++ Code Render Version 0.01 Beta
4
5 #include <iostream>
6 using namespace std;
7
8 /* 用普通递归会超时,改用记忆递归法(将数据存储在数组里)
9 int m;
10
11 int f(int n)
12 {
13 if(n>m)
14 return 0;
15 else if(n==m)
16 return 1;
17 else
18 return f(n+1)+f(n+2);
19 }
20 */
21
22 int main()
23 {
24 /*
25 int T;
26 cin>>T;
27 while(T--){
28 cin>>m;
29 cout<<f(1)<<endl;
30 }
31 */
32
33 int a[41];
34 a[1]=1,a[2]=1;
35
36 for(int i=3;i<=40;i++) //记忆递归法。牺牲空间,换取时间。
37 a[i]=a[i-1]+a[i-2];
38
39 int T,m;
40 cin>>T;
41 while(T--){
42 cin>>m;
43 cout<<a[m]<<endl;
44 }
45 return 0;
46 }
Freecode : www.cnblogs.com/yym2013