您的位置:首页 > 编程语言 > Java开发

兔子问题----算法基础

2016-12-21 09:41 218 查看
每日一练,坚持就是胜利。

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?



程序分析:第一个月一对兔子,第二个月一对兔子,第三个月两对兔子,第四个月三对兔子,第五个月五对兔子…………由此可以推出一个数字序列。1、1、2、3、5、8、13、21……由此可以发现这些数字的规律:前两个数之和等于第三个数,这样程序就出来了



/**
* 递归的算法
* @param mounth
* @return
*/
public static int address(int mounth) {
if (mounth == 1 || mounth ==2) {
return 1;
}else {
return address(mounth - 1) + address(mounth - 2);
}
}


/**
* 循环的算法
* @param mounth
* @return
*/
public static int reserve(int mounth) {

int[] num = new int[mounth+1];
num[0] = 0;
num[1] = 1;

int index = 2;
if (mounth>1) {
while (index < mounth+1) {
num[index] = num[index - 1] + num[index - 2];
index++;
}
}

return num[mounth];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法