Problem
ProblemRecall the definition of the Fibonacci numbers from “Rabbits and Recurrence Relations”, which followed the recurrence relation Fn=Fn−1+Fn−2 and assumed that each pair of rabbits reaches maturity in one month and produces a single pair of offspring (one male, one female) each subsequent month.Our aim is to somehow modify this recurrence relation to achieve a dynamic programming solution in the case that all rabbits die out after a fixed number of months. See Figure 4 for a depiction of a rabbit tree in which rabbits live for three months (meaning that they reproduce only twice before dying).
兔子繁殖问题
假定如下,
- 种群在第一个月开始时有一对新生兔子。
- 一个月后兔子达到生育年龄。
- 在任何给定的月份,每只育龄兔子都会与另一只育龄兔子交配。
- 两只兔子交配一个月后,它们会生出一只雄性兔子和一只雌性兔子。
- 兔子有n个月的寿命
问题:input: 对于给定的月份n,兔子的寿命k, 每次死亡的兔子数量moutput: 兔子总对数
n = 6, rabbit_life = 3, rabbit_die_num = 1output: 4
思路:
- 利用递归解决 兔子在寿终正寝前的数量符合斐波那契数列,在出现死亡的第一个月时,每个月都会有
m只兔子死亡,减去相应的死亡数量即可solution -1
```python def rabbit_fab2(n, rabbit_life = 3, rabbit_die_num = 1): if n <= 2:
if n > 2 and n <= rabbit_life:return 1
else:return rabbit_fab2(n - 2) + rabbit_fab2(n - 1)
return rabbit_fab2(n - 2) + rabbit_fab2(n - 1) - rabbit_die_num
def main(): rabbit_fab2(n = 6)
if name == ‘main‘ main() ```
