brute force and memoization(not tested)