您的位置:首页 > 其它

一头母牛,三年后,这头母牛每年会生出1头母牛, 生出来的母牛三年后,又可以每年生出一头母牛

2013-04-28 15:27 344 查看
该题是蓝桥杯上的一道填空题。应该是为了考察集合的使用吧,代码看上去有些臃肿,不过解题思想很好,就是效率太低了。mark一下。

让我想到了大一时候学习递归时候用的方法,但那时根本没有想过执行效率的问题。

在此我写出四种解法。

至于递归方法,简洁,但效率就低多了去了。

本题不难,只是随便比较一下执行效率,高手请手下留情。

n取32,太大了方法四就堆溢出了,再大就超过int存储长度了。

上代码:

import java.util.ArrayList;
import java.util.List;
class Cow
{
	static int f[]=new int[1000];
	//方案一:该年的母牛个数等于 前年的母牛个数(生一个小牛)  加上  去年的母牛个数
	static int f(int n)
	{
		return n>2 ? f(n-2)+f(n-1) : 1; 
	}
	
	//方案二:打表提高执行效率
	static int f2(int n)
	{
		for(int i=1;i<n;i++) g(i);
		return g(n);
	}
	static int g(int n)
	{
		f
 = n>2 ? f[n-2]+f[n-1]:1;
		return f
;
	}
	
	//方案二:迭代节省空间同时提高执行效率
	static int f3(int n)
	{
		int a,b,sum;
		a=b=sum=1;
		for(int i=3;i<=n;i++)
		{
			sum=a+b;
			a=b;
			b=sum;
		}
		return sum;
	}
	
	
	//方案四:直接模拟母牛生产过程
	private int age;
	public Cow afterYear()
	{
		age++;
		return age > 2 ? new Cow() :null;//填空
	}	
	
	public static void f4(int n)
	{
		List<Cow> list = new ArrayList<Cow>();
		list.add(new Cow());

		for (int i = 0; i < n; i++)
		{
			int cowCount = list.size();
			for (int j = 0; j < cowCount; j++)
			{
				Cow cow = list.get(j).afterYear(); 
				if (cow != null)
				{
					cow.age++;// 填空
					list.add(cow);
				}
			}
			
		}
		System.out.println(list.size());		
	}
	
	
	
	public static void main(String[] args) throws Exception 
	{
		long start=System.nanoTime();
		System.out.print("方案一:");
		System.out.println(f(32));
		System.out.println(System.nanoTime()-start);
		start=System.nanoTime();
		
		System.out.print("方案二:");
		System.out.println(f2(32));
		System.out.println(System.nanoTime()-start);
		start=System.nanoTime();
		
		System.out.print("方案三:");
		System.out.println(f3(32));
		System.out.println(System.nanoTime()-start);
		start=System.nanoTime();
		
		System.out.print("方案四:");
		f4(32);
		System.out.println(System.nanoTime()-start);
    }
 }
//方案一:2178309
//10237153
//方案二:2178309
//59283
//方案三:2178309
//45040
//方案四:2178309
//473797733


可以看出方法一直接递归效率是非常慢的,方法二和方法三在同一个数量级。至于方法四,我想说蓝桥杯上的方法也太水了吧。。。整整多了四个数量级。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐