Refactored solve_rec