题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395
#这是一个经典递归问题,也可以用动态规划算法求解 #1.动态规划 def rabbit_population(n): if n == 1 or n == 2: return 1 adults = 1 junior = 1 for i in range(3,n+1): new_rabbit = adults adults,junior = new_rabbit + junior,new_rabbit return adults if __name__=='__main__': n = int(input()) print(rabbit_population(n))
F(1) = 1
F(2) = 1
F(3) = 1+1
F(4) = 1+1+1
F(5) = 1+1+1+1+1
......
找到规律F(n) = F(n-1)+F(n-2)
或设置一个循环迭代过程range(3,n+1),初始化adults = 1,junior = 1,--->new_rabbit = adults, adults,junior =new_rabbit + junior,new_rabbit