solved using recursion and caching