Java:演算法 - 開局一對兔,兩月就成熟
阿新 • • 發佈:2018-12-26
題目:古典問題:有一對兔子,從出生後第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);
}
}