• hdu 2041:超级楼梯(水题,递归)


    超级楼梯
    
    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 }

     


      第二次做。

      水题。

      常规做法会超时,输出几组连续的测试数据会发现,输出结果是斐波那契数列。那么题目就简单了,直接构造一个40以内的斐波那契数列即可,f1=1,f2=1。

      常规做法是写一个递归,作用是记录当前走到了哪一级阶梯(假设为n),所以出口是当n>M(直接return;)或者n==M(sum++;return ;),递归体是f(n+1)然后f(n+2),分别表示当前走1级阶梯和2级阶梯的情况。

      代码:

     1 #include <iostream>
     2 
     3 using namespace std;
     4 int sum;
     5 int m;
     6 int a[41];
     7 void f()
     8 {
     9     a[1] = 1;
    10     a[2] = 1;
    11     for(int i=3;i<=40;i++)
    12         a[i] = a[i-1] + a[i-2];
    13 }
    14 int main()
    15 {
    16     int n;
    17     f();
    18     cin>>n;
    19     while(n--){
    20         cin>>m;
    21         cout<<a[m]<<endl;
    22     }
    23     return 0;
    24 }

     

    Freecode : www.cnblogs.com/yym2013

  • 相关阅读:
    使用supervisor过程的坑
    为apache安装mod_wsgi的时候出现-fpic的问题
    信息生成二维码的方法
    mac下virtualbox安装win7系统
    js读取json方法
    如何读取抓取的wifi包内容
    python文章学习列表
    sqlserver中drop、truncate和delete语句的用法
    UE中使用正则表达式的一些技巧
    指定IE浏览器渲染方式
  • 原文地址:https://www.cnblogs.com/yym2013/p/3254616.html
Copyright © 2020-2023  润新知