Solve #14 with memoization