using hashset instead of treeset was not enough. looks like we need to use memoization