0

I am trying to use memoization in order to calculate catalan numbers, but it just does not seem to work, what do I need to change?

def catalan_mem(n, mem = None):
    if n==0:
        return 1
    if mem==None:
        mem={}
    sum=0
    if n not in mem:
        for i in range(0, n):
            sum = sum + catalan_mem(i) * catalan_mem(n-i-1)
        mem[n]=sum
    return mem[n] 
Guy Coder
  • 24,501
  • 8
  • 71
  • 136

1 Answers1

0

You need to pass the cache to your recursive calls:

sum = sum + catalan_mem(i, mem) * catalan_mem(n-i-1, mem)

Otherwise, every method call creates a new empty cache.

user2390182
  • 72,016
  • 6
  • 67
  • 89