Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Classical problem: have a pair of rabbits, from be born after 3 months every month all give birth to a pair of rabbits, little rabbit child grows to after 3 months every month give birth to a pair of rabbits again, if rabbit all die, ask the total number of rabbits of each month for how many

January: 1 to January: 1 to February: 1 to March: 2 to April: 3 to May: 5 to June: 8 to January: 1 to February: 1 to March: 2 to April: 3 to May: 5 to June: 8

The number of rabbits in the NTH month is the sum of the number of rabbits in the previous month and the number of rabbits in the previous month. The first method is to use brute force.

public class title01 { public static void main(String[] args) { int sum[] = new int[12]; for(int i =1 ; i <= 12; i++){ if(i == 1 || i==2){ sum[i-1] = 1; }else{ sum[i - 1] = sum[i-2]+sum[i-3]; } } for(int i = 0; i<12 ; I++) {System. Out. Println (I + 1 + ":" + sum [I] + ""); }}Copy the code

The second approach is to use a recursive algorithm

public class title01_1 {
public static int sum(int n){
	if(n >= 13){
		return 0;
	}
	if(n == 1 || n == 2){
		return 1;
	}else{
		return sum(n-1) + sum(n-2);
	}
}
public static void main(String[] args) {
	for(int i = 1; i<= 12; i++){
		System.out.println(i + "月:" + sum(i) + "对");
	}
}
}
Copy the code

The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610, where the 0th term is 0, the first term is the first 1, and the sequence starts with the third term, Each term is equal to the sum of the first two terms.) And his implementation is shown in the example above of the undead rabbit and you can see that using recursion you can see what he’s thinking. Of course, there are many ways to implement it and recursion is probably a relatively easy way to implement it and understand it