母牛每年生一头小牛。一头小牛在两年内变成了一头牛,从一头牛开始,我们必须数一数N年内有多少动物。假设没有一头牛死了。
例如在N=5:
第一头母牛生了两头小牛(1头在2岁,另一头在3岁,其次是4头,接下来是5头) total= 4头牛现在也已经3岁了,所以(她在2岁时生了1头牛,另一头在3岁时生了1头牛)总数=2头牛。第二头母牛也必须是2岁,所以她刚刚生了另一头小牛,总共=1头小牛。
sum = 1+4+2+1
随着年份的增加,休会继续进行。
我最近在一次考试中得到了这个问题。我试着使用递归,我只是一个初学者,我不能正确地使用它。
public static void main(String args[]) {
Scanner sc =new Scanner(System.in);
int n= sc.nextInt();
sc.close();
fun(n);
}
public static void fun(int age) {
int arr[] = new int[age-1];
int temp=0, sum=1;
for(int i=age-2; i>=0; i--){
arr[temp++]=i;
}
sum+=arr.length;
for(int j=0; j<age-1; j++) {
if(arr[j]>=2) {
fun(j);
}
}
System.out.println(sum);
}发布于 2020-01-27 16:58:32
你可以试试这个。它不是递归的(这是一个严格的要求吗?)但它得到了正确的答案:
import java.util.ArrayList;
import java.util.List;
public class Bovines {
private static final class Bovine {
private final int birthYear;
public Bovine(final int birthYear) {
this.birthYear = birthYear;
}
public boolean isCow(final int year) {
return (year - this.birthYear) >= 2;
}
}
public static void main(final String[] args) throws Exception {
final List<Bovine> bovineList = new ArrayList<>();
/**/ bovineList.add(new Bovine(0)); // (initial Calf)
for (int year=0; year <= 5; year++) {
/*
* Iterate over a copy of the List to avoid any parallel-update issues...
*/
for (final Bovine bovine : new ArrayList<>(bovineList)) {
if (bovine.isCow(year)) {
bovineList.add(new Bovine(year)); // (Cow has Calf)
}
}
System.out.println("Year.: " + year + " Total: " + bovineList.size());
}
}
}发布于 2020-01-27 17:07:09
也许这个问题有更有效的实现,但在我看来,以下是易于解释和理解的:
public class CowCalculator {
public static int numberOfCows(int maxAge) {
int count = 1; // the "root" cow
for (int year = 2; year <= maxAge; year++) {
// after the second year, the "root" cow gives birth to one calve every year
// every calve is a root cow by itself, but with less maximum age
count += numberOfCows(maxAge - year);
}
return count;
}
public static void main(String[] args) {
System.out.println(CowCalculator.numberOfCows(5));
}
}发布于 2021-09-23 22:27:04
int main()
{
printf("%d\n", cowCount(6));
return 0;
}
int getNumOfCows(int year){
if(year < 0) return -1;
if(year >= 0 && year <= 2) return 1;
if(year > 2) return year - 1;
}
int getCowsCount(int year){
int sum = 0;
for(int y=0; y<=year; y++){
sum += getNumOfCows(y);
}
return sum;
}https://stackoverflow.com/questions/59926908
复制相似问题