Problem
Recall the definition of the Fibonacci numbers from “Rabbits and Recurrence Relations”, which followed the recurrence relation Fn=Fn−1+Fn−2Fn=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).
Given: Positive integers n≤100n≤100 and m≤20m≤20.
Return: The total number of pairs of rabbits that will remain after the nn-th month if all rabbits live for mm months.
Sample Dataset
6 3
Sample Output
4
# coding=utf-8 ### 11. Mortal Fibonacci Rabbits ### # 0 1 1 2 2 3 4 5 7 9 12 # method1 def fibonacciRabbits(n, m): F = [0, 1, 1] for i in range(3, n + 1): if i <= m: total = F[i - 1] + F[i - 2] elif i == m + 1: total = F[i - 1] + F[i - 2] - 1 else: total = F[i - 1] + F[i - 2] - F[i - m - 1] F.append(total) return (F[n]) # print fibonacciRabbits(6,3) # method2 def f(n, k): s = [0] * (k + 1) # list *4 [0, 0, 0, 0] s[0]代表当月出生的兔子,s[k]代表当月死亡的兔子 s[0] = 1 # [1, 0, 0, 0] for x in range(1, n): s[1:k + 1] = s[0:k] print s s[0] = sum(s[2:]) return sum(s[:-1]) print f(10, 3)