Problem

11 Mortal Fibonacci Rabbits
Figure 4. A figure illustrating the propagation of Fibonacci's rabbits if they die after three months.

Recall 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).

Given: Positive integers m≤20.

Return: The total number of pairs of rabbits that will remain after the m 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)

  

相关文章:

  • 2021-08-15
  • 2022-12-23
  • 2021-10-26
  • 2022-02-05
  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
  • 2021-12-08
猜你喜欢
  • 2021-06-14
  • 2021-06-17
  • 2022-01-27
  • 2021-08-19
  • 2021-12-02
  • 2022-12-23
  • 2021-07-27
相关资源
相似解决方案