Refactor and improve performance of solver with caching.