py递归3TLE 2RE萌新求大佬解答(难过

P1255 数楼梯

frq114514 @ 2024-06-06 21:39:09

a=int(input()) def f(n): if n<=2: return n else: return f(n-1)+f(n-2) print(f(a))


by Qian__Feng @ 2024-06-06 21:43:25

包超时的,你要用递归的话,需要记忆化搜索。


by Terrible @ 2024-06-06 21:49:30

import sys
import functools
sys.setrecursionlimit(1000000)
@functools.lru_cache(maxsize=5000)
def fib(n):
    if n<=2:return n
    return fib(n-1)+fib(n-2)
n=int(input())
print(fib(n))

by Lby_jason @ 2024-06-06 22:11:39

用高精度 数据我试过 爆usingent long long


by Lby_jason @ 2024-06-06 22:13:47

还要记忆化


by Lby_jason @ 2024-06-06 22:15:02

@Lby_jason 我说的是暴力 虽然能过


by Lby_jason @ 2024-06-06 22:18:02

毕竟是前面的题 递归还更复杂


by Lby_jason @ 2024-06-06 22:20:23

如果用递归 记忆和longlong必须有

毕竟 “十年oi一场空,不开longlong见祖宗”


by Limingxuan8864 @ 2024-06-07 16:54:41

@qian_feng 包的呀!


by znzryb @ 2024-07-08 18:35:06

RE是因为递归深度不够,TLE可能是没用缓存

import sys
sys.setrecursionlimit(10000) # 增加递归深度限制
mem={}
def count(n,mem):
    if n == 1:
        mem[1]=1
        return 1
    elif n == 2:
        mem[2]=2
        return 2
    else:
        if n in mem:
            return mem[n]
        else:
            mem[n]=count(n - 1, mem) + count(n - 2, mem)
            return mem[n]

n = int(input())
print(count(n,mem))

by liuxuanrui000 @ 2024-07-10 14:30:49

@Lby_jason 你说的是c++


| 下一页