Use memorization to cache the results, but ran into memory limit exceed problem.