题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?
程序分析:哇是斐波那契数列1,1,2,3,5,8,13,21… 用递归fn = fn-1 +fn-2
吐槽:题干别读成小兔子长到第三个月后(的第四个月)又生了一对兔子,这样递归会变成fn = fn-2+fn-3+fn-4…,小兔子是2周月就成熟!
递归解法:从第三月开始,总数为前2个月的和:
public static int countPairsOfRabbits(int month) throws Exception{
if(month == 1 || month == 2){
return 1;
}else if(month <=0){
throw new Exception("invalid argument of month");
}else{
return countPairsOfRabbits(month-1)+countPairsOfRabbits(month-2);
}
}
如果要问每个月小兔子和大兔子的对数怎么办?
对数: 小兔+大兔=兔子
初始1对小兔,花2个月变成大兔子,然后大兔子生同样数量的小兔。
可以把小兔放进一个长度2的数组,模拟队列,出列合并大兔生仔~
public static void countRabbitAndBunny(int month) throws Exception{
if(month == 1 || month == 2){
System.out.println("Pairs: Sum: 1 || Rabbit: 0 || Bunny: 1");
}else if(month <=0){
throw new Exception("invalid argument of month");
}else{
//where we found our bunnies
int[] bunny = new int[2];
/*
* the second month status
*/
bunny[1] = 1; //bunny of month 2 in the array
int pairOfBunny = 1;
int pairOfRabbit = 0;
int sum = pairOfBunny + pairOfRabbit;
//count the "i"th month status
for(int i=3;i<=month;i++){
//bunnies became rabbits
pairOfRabbit = pairOfRabbit + bunny[1];
pairOfBunny = pairOfBunny - bunny[1];
//some bunnies grew up
bunny[1] = bunny[0];
//some bunnies were just born
bunny[0] = pairOfRabbit;
pairOfBunny = pairOfBunny + bunny[0];
//count all rabbits alive
sum = pairOfBunny + pairOfRabbit;
}
//we now have the result
System.out.println("Pairs: Sum: " + sum + "|| Rabbit: "
+ pairOfRabbit + " || Bunny: "+pairOfBunny);
}
}