modified recursive function.
applying memoization