动态规划 ≈ 分治法 + memo
def memo(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
@memo # 注释掉这个装饰器
def fib(i):
if i < 2:
return 1
return fib(i-1) + fib(i-2)
print(fib(55))
cache = {}
def memo(func):
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
@memo
def fib(i):
if i < 2:
return 1
return fib(i-1) + fib(i-2)
print(fib(55))
print(cache)
另外,关于*args当参数传函数为unpack
def foo(*args):
print(args)
args = (1,2,34,)
foo(*args)
foo(args)