Given a set of constraints, how would you optimize this recursive function to prevent redundant calculations?