题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395
#这是一个经典递归问题,也可以用动态规划算法求解 #1.动态规划 def rabbit_population(n): if n == 1 or n == 2: return 1 junior = 1 adults = 1 for _ in range(3,n+1): new_rabbit = adults adults,junior = new_rabbit + junior,new_rabbit return adults #2.递归算法 def fabonacci(n): if n == 1 or n == 2: return 1 else: return fabonacci(n-1)+fabonacci(n-2) if __name__=='__main__': n = int(input()) print(fabonacci(n)) #共有两种算法,用递归就比较容易实现也比较好想出来;用动态规划迭代,range(3,n+1),初始化junior,adults取值1,每一次迭代更新junior和adults分别为new_rabbit和new_rabbit+junior,其中new_rabbit = adults