每日一练,坚持就是胜利。
题目:古典问题:有一对兔子,从出生后第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];
}