我是靠谱客的博主 还单身纸鹤,这篇文章主要介绍老鼠生子问题,现在分享给大家,希望可以做个参考。

很久没自己动手写过程序了,今天从一个QQ群里看到有人问这个问题,就想自己动手试一下,结果手足无措,发现自己真的是老了,智商跟不上了。

算法什么的,什么也不会了,刚接触了几天 Java,试着用 Java 写了一下,不知道写的对不对?

经典的耗子生子问题。
假设一对耗子每个月都可以生一对小耗子。小耗子生长3个月后,从第4个月开始也就能够生小耗子。
问:假设所有的耗子都不死的话,那么20个月后一共有多少只耗子?

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
复制代码
import java.util.ArrayList;
public class MyTest
{
public static void main(String[] args)
{
MiceCouple m = new MiceCouple();
int count = 0;
for(int i = 0; i < 20 ; i++)
{
m.grow();
count = m.getChildrentCount() + 1;
System.out.println("" + count);
}
count = m.getChildrentCount() + 1;
System.out.println("" + count);
}
}
class MiceCouple
{
private int age;
private ArrayList<MiceCouple> children;
public MiceCouple()
{
this.age = 0;
this.children = new ArrayList<MiceCouple>();
}
public void grow()
{
this.age++;
if(this.age > 3)
this.breed();
for(MiceCouple m : this.children)
{
m.grow();
}
}
private void breed()
{
children.add(new MiceCouple());
}
public int getChildrentCount()
{
int sum = 0;
for(MiceCouple m : children)
{
sum += m.getChildrentCount();
}
sum += children.size();
return sum;
}
}

复制代码

结果:(20个月)
1
1
1
2
3
4
6
9
13
19
28
41
60
88
129
189
277
406
595
872

 

最后

以上就是还单身纸鹤最近收集整理的关于老鼠生子问题的全部内容,更多相关老鼠生子问题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(142)

评论列表共有 0 条评论

立即
投稿
返回
顶部