Chinaunix首页 | 论坛 | 博客
  • 博客访问: 181045
  • 博文数量: 14
  • 博客积分: 1403
  • 博客等级: 上尉
  • 技术积分: 192
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-18 16:36
文章分类

全部博文(14)

文章存档

2011年(5)

2010年(9)

分类: C/C++

2011-01-09 23:54:10

大牛生小牛问题,刚出生的小牛,长四年就可以每年生小牛一头。现有一头刚出生的小牛,算出20年后共有多少头牛。

一如既往,递归的烂效率实在无语。

相比起来,更喜欢递推。递推中使用了数组,正好熟悉c#中数组的定义和使用。

代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace c4_t6
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("递归算法:{0}", getCount(20));
            Console.WriteLine("递推算法:{0}", getCountEasy(20));
            Console.ReadLine();
        }

        //递归算法,y指y年后小牛个数

        static int getCount(int y)
        {
            if (y < 4)
            {
                return 1;
            }
            else
            {
                return getCount(y - 1) + getCount(y - 4);
            }
        }

        //递推算法,y指y年后小牛个数

        static int getCountEasy(int y)
        {
            int[] a = new int[5] { 1, 1, 1, 1, 0 };
            if (y < 4)
            {
                return 1;
            }
            else
            {
                for (int i = 4; i <= y; i++)
                {
                    a[4] = a[3] + a[0];
                    a[0] = a[1];
                    a[1] = a[2];
                    a[2] = a[3];
                    a[3] = a[4];
                }
                return a[4];
            }
        }
    }
}


阅读(2752) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~