To solve this problem to note: Find the recursive method body, recursive export.
Package com.cc; /**
*
* There are a pair of rabbits, from the third month after the birth of a pair of rabbits each month, the rabbit long to the third month after the birth of a pair of rabbits each month, if the rabbit is not dead, ask the total number of rabbits each month.
* @author liukeqing
*
*/
public class Hello {
public static void Main (string[] args) {
int month = 8;//first few months
int sum = getcount (month);//Get the total number of rabbits this month
System.out.println ("The first" +month+ "Month born Rabbit:" +sum + "only");
}
The design idea of recursive algorithm: for a complex problem, the original problem is decomposed into several relatively simple and identical sub problems. Continue until the child problem is simple enough to be solved directly.
/**
* Get the total number of bunnies = The total number of rabbits + newborn rabbit total = last month (n-1) The total number of rabbits + last month (n-2) The total number of rabbits
* @param month the first few months
* @return
*/
private static int getcount (int month) {
int sum = 0;//monthly Rabbit Total
if (month = = 1 | | month ==2) {//The first month and the second month of each pair of rabbits are barren, the rabbits are a pair
sum = 2;
}else{//Rabbit begins to bear
sum = GetCount (month-1) + GetCount (month-2);
}
return sum;
}
}