def fact(n, memo):
if n == 0: return 1
if n not in memo:
memo[n] = n*fact(n-1, memo)
return memo[n]
客户端(调用端):
if __name__ == '__main__':
memo = {}
print([fact(n, memo) for n in range(100)])
或者:
def fact(n, memo):
if n not in memo:
memo[n] = n*fact(n-1, memo)
return memo[n]
if __name__ == '__main__':
memo = {0:1}
print([fact(n, memo) for n in range(100)])
注:本例虽然有动态规划的形式(记忆体),却无动态规划的实质,不存在重叠子问题,自然也就没有最优子结构,仍属简单的递归求解。