一个农夫养了一头牛,三年后,这头牛每年会生出1头牛,生出来的牛三年后,又可以每年生出一头牛……问农夫10年后有多少头牛?n年呢?
1.
public class Cow {
static int count = 1;
private static void feedCow(int year,int age){
year++;
age++;
if(year<=30){
if(age>=3){
count++;
feedCow(year,0);
}
feedCow(year,age);
}
}
public static void main(String[] args) {
new Cow().feedCow(0, 0);
System.out.println(count);
}
}
2.
public class Cow {
public static int count = 0;
public Cow(int year){
count++;
for(int i=3+year;i<=10;i++){
new Cow(i);
}
}
public static void main(String[] args) {
new Cow(0);
System.out.println(count);
}
}
3.
public class Cow {
private int age;
public Cow(){
age = 0;
}
public Cow play(){
age ++;
return age > 3 ? new Cow():null;
}
public static void main(String[] args) {
List<Cow> list = new ArrayList<Cow>();
list.add(new Cow());
for(int i = 0; i <= 10;i++){
for(int j =0;j<list.size();j++){
Cow cow = list.get(j).play();
if(cow != null)
list.add(cow);
}
}
System.out.println("10年后,共有:" + list.size());
}
}