1. 递归(有递归次数限制)nums = {1:1, 2:2}
import functools
@functools.cache
def dp(n):
try:
return nums[n]
except:
return dp(n-1) + dp(n-2)
print(dp(int(input())))
2.递归(无递归次数限制)nums = {1:1, 2:2}
import functools
@functools.cache
def dp(n):
try:
return nums[n]
except:
return dp(n-1) + dp(n-2)
count = 500
n = int(input())
while True:
if n < count:
print(dp(n))
break
nums_ = dict()
nums_[count], nums_[count-1] = dp(count), dp(count-1)
nums = nums_
count += 500
3.循环n = int(input())
if n == 1:
print(1)
elif n == 2:
print(2)
else:
nums = [1, 2]
i = 2
while i < n:
nums.append(nums[i-2] + nums[i-1])
i += 1
print(nums[-1])
|