【发布时间】:2021-12-16 14:24:40
【问题描述】:
输入
sum_possible(2017, [4, 2, 10]) # -> False
使用any 导致RecursionError: maximum recursion depth exceeded
def sum_possible(amount, numbers, cache = None):
if cache is None:
cache = {}
if amount in cache:
return cache[amount]
if amount == 0:
return True
if amount < 0:
return False
cache[amount] = any(sum_possible(amount - number, numbers, cache) for number in numbers)
return cache[amount]
使用解决方案的for 循环
def sum_possible(amount, numbers, cache = None):
if cache is None:
cache = {}
if amount in cache:
return cache[amount]
if amount == 0:
return True
if amount < 0:
return False
for number in numbers:
if sum_possible(amount - number, numbers, cache):
cache[amount] = True
return True
cache[amount] = False
return False
【问题讨论】:
标签: python recursion caching dynamic-programming