Added memoized recursive algorithm