题解 | #斐波那契数列#
斐波那契数列
https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param n int整型
# @return int整型
#
class Solution:
def Fibonacci(self , n: int) -> int:
a = 1
b = 1
c = 1
i = 3
while i <= n:
c = a + b
a = b
b = c
i += 1
return c
不同于递归的思路,把n从大到小逐步拆解到1,2,再从小到大反向聚合。这个思路是直接从小值开始往上汇聚,且只用三个变量保存每次计算时相邻的f(n)和f(n-2)、f(n-1)

查看13道真题和解析