以动态规划版的斐波那切数列为例,进行说明:
作为全局变量
memo = {0:0, 1:1}
def fib(n):
global memo
if n not in memo:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
作为参数
def fib(n, memo):
if n not in memo:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
这样需在客户端(调用端),传递进该参数,
memo = {0:0, 1:1}
[fib(i, memo) for i in range(100)]