memorization(overlapping subproblems) demo

来源:互联网 发布:java 内部类构造函数 编辑:程序博客网 时间:2024/06/04 22:03
#quote from 'introduction to computation and programming using python,# revised edition, MIT'def fastFib(n, memo = {}):    """Assumes n is an int >= 0, memo used only by recursive calls       Returns Fibonacci of n"""    if n == 0 or n == 1:        return 1    try:        return memo[n]    except KeyError:        result = fastFib(n-1, memo) + fastFib(n-2, memo)        memo[n] = result        return result

0 0