• 小牛生产小牛的问题解决集粹


    问题:
              一只刚出生的小牛,4年后生一只小牛,以后每年生一只。现有一只刚出生的小牛,问N年后共有牛多少只?


    1.原始笨方法
    private int Comput(int years)
            
    {
                
    //初始化为1头牛
                int count = 1;
                
    if (years < 4)
              
    {
                    
    return count;
                }

                
                
    while (years - 3 > 0)
                
    {
                    count 
    = count + Comput(years - 3);
                    years
    --;
                }

                
    return count;


            }
    特点:容易理解,不过效率太低.不具有实用价值.

    2.采用HashTable优化方案
    Hashtable table = new Hashtable();
            
    public long Compute(int years)
            
    {
                
    //初始化为1头牛
                long count = 1;
                
    if (years <= 3)
              
    {
                    
    return count;
                }

                
    int i = 4;
                
    while (i <= years)
                
    {
                    
    int subYears = i - 3;
                    
    if (table.ContainsKey(subYears))
                  
    {
                        count 
    = (long)table[subYears];
                    }

                    
    else
                  
    {
                        count 
    += Compute((int)(subYears));
                    }

                    
    if (!table.ContainsKey(subYears))
                  
    {
                        table.Add(subYears, count);
                    }

                    i
    ++;
                }

                
    return (long)count;
            }
    特点:在第一种方案的基础上性能有了大幅度的提高.采用HashTable存储老牛的生育曲线,从而达到以后的小牛重复利用老牛的生育曲线.(直接取其生产数量)

    3.采用数组的方式描述
    public int Compute(int years)
            
    {
              
    int[] age = new int[41000 };
                
    for (int i = 2; i <= years; i++)
                
    {
                    age[
    3+= age[2];              age[2= age[1]; 
                    age[
    1= age[0];
                    age[
    0= age[3];                 

                }

                
    return (age[0+ age[1+ age[2+ age[3]);
            }

    特点:只采用一个循环搞定,效率极高.

    3.采用优化递归公式实现
     f(n)   =   f(n-1)+f(n-3)  [n   >   3]   
     f(n)   =   1                   [0   <   n   <=   3]  
    public int Comput(int x)
          
    {
                
    if (x < 4return 1;
                
    else return Comput(x - 1+ Comput(x - 3);
            }
       

    特点:代码简洁,功能简单实现,但使用递归当然会牺牲一定的效率作为代价.

    前些天在网络上偶然发现的生产小牛问题.于是搜集整理了一下,方便大家共同研究学习使用.
    有好的算法大家共同研究^_^

  • 相关阅读:
    RAID实战案例
    文件系统常用工具实战篇
    挂载文件系统
    硬盘结构类型概述
    创建文件系统实战篇
    JumpServer的会话管理及命令过滤器应用案例
    JumpServer的权限管理
    JumpServer的用户管理
    helm基础
    hpa控制器
  • 原文地址:https://www.cnblogs.com/symbol441/p/1073291.html
Copyright © 2020-2023  润新知