一个农夫养了一头牛,三年后,这头牛每年会生出1头牛,生出来的牛三年后,又可以每年生出一头牛……问农夫10年后有多少头牛?n年呢?(用JAVA实现)
很有名的一道题,11楼放出最经典的两种解题思路,大家先试试
1
.
package cn.edu.nankai;
import java.util.HashSet;
import java.util.Set;
class Cow
{
private int age;
public Cow()
{
age = 0 ;
}
public Cow bearCow() // 生小牛
{
return new Cow();
}
public void grow() // 每年牛龄加1
{
age = age + 1 ;
}
public int getAge()
{
return age;
}
}
public class Main {
private static Set cowSet = new HashSet (); // 牛圈,存放所有的牛
public static int check() // 每年检测一遍所有的牛,年龄要加一,并且够岁数了要生效牛
{
Set newCowSet = new HashSet ();
for (Cow cow : cowSet)
{
cow.grow(); // 年龄加一
if (cow.getAge() >= 3 )
newCowSet.add(cow.bearCow()); // 够岁数的生小牛
}
cowSet.addAll(newCowSet); // 把所有生出来的小牛放牛圈里
return cowSet.size();
}
public static void main(String args[])
{
Cow cow = new Cow();
cowSet.add(cow);
for ( int i = 0 ; i < 10 ; i ++ )
{
System.out.println(i + 1 + " : " + check());
}
}
}
回复评论
删除
1 .
Smith的头像
Smith 2009 / 10 / 31 21 : 12
public class Cow {
public static int coun = 1 ;
public static void main(String args[]) {
new Cow().cowY( 10 );
System.out.println(coun);
// System.out.println(Cow.getNum(10));
}
public static int getNum( int i) {
if (i < 3 ) {
return 1 ;
} else {
return getNum(i - 1 ) + getNum(i - 2 );
}
}
public void cowY( int year) {
int age = 1 ;
while (age <= year) {
age ++ ;
if (age <= year && age >= 3 ) {
coun ++ ;
cowY(year - age);
}
}
}
}
package cn.edu.nankai;
import java.util.HashSet;
import java.util.Set;
class Cow
{
private int age;
public Cow()
{
age = 0 ;
}
public Cow bearCow() // 生小牛
{
return new Cow();
}
public void grow() // 每年牛龄加1
{
age = age + 1 ;
}
public int getAge()
{
return age;
}
}
public class Main {
private static Set cowSet = new HashSet (); // 牛圈,存放所有的牛
public static int check() // 每年检测一遍所有的牛,年龄要加一,并且够岁数了要生效牛
{
Set newCowSet = new HashSet ();
for (Cow cow : cowSet)
{
cow.grow(); // 年龄加一
if (cow.getAge() >= 3 )
newCowSet.add(cow.bearCow()); // 够岁数的生小牛
}
cowSet.addAll(newCowSet); // 把所有生出来的小牛放牛圈里
return cowSet.size();
}
public static void main(String args[])
{
Cow cow = new Cow();
cowSet.add(cow);
for ( int i = 0 ; i < 10 ; i ++ )
{
System.out.println(i + 1 + " : " + check());
}
}
}
回复评论
删除
1 .
Smith的头像
Smith 2009 / 10 / 31 21 : 12
public class Cow {
public static int coun = 1 ;
public static void main(String args[]) {
new Cow().cowY( 10 );
System.out.println(coun);
// System.out.println(Cow.getNum(10));
}
public static int getNum( int i) {
if (i < 3 ) {
return 1 ;
} else {
return getNum(i - 1 ) + getNum(i - 2 );
}
}
public void cowY( int year) {
int age = 1 ;
while (age <= year) {
age ++ ;
if (age <= year && age >= 3 ) {
coun ++ ;
cowY(year - age);
}
}
}
}