zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    简识UML语言(转)
    很好的理解遗传算法的样例
    strtok和strtok_r
    HDU 11488 Hyper Prefix Sets (字符串-Trie树)
    深入浅出JMS(一)——JMS简单介绍
    CSS3学习----选择器、字体
    消息中间件的技术选型心得-RabbitMQ、ActiveMQ和ZeroMQ
    【LeetCode】Sum Root to Leaf Numbers
    选择用户-显示已选用户
    ajax异步通讯 遮罩滚动栏,防止并发及误操作
  • 原文地址:https://www.cnblogs.com/yym2013/p/3254616.html
Copyright © 2011-2022 走看看