Fixed memoization so it works with all inputs, inc. lists, sets, dicts.