Ad matrix dynamic programming using memoiztion implementation