Solution Review: The Knapsack Problem
Explore how to solve the knapsack problem by applying top-down dynamic programming with memoization. Understand the recursive approach, recognize optimal substructure and overlapping subproblems, and learn to optimize time complexity by storing intermediate results.
Solution 1: Simple recursion
Explanation
Let’s go over the intuition of the problem before moving on to the explanation of the code. Remember your goal was to select a subset of objects which return the maximum total profit while obeying the constraint that their weight is less than or equal to the total capacity of the knapsack. Now any object, let’s say a book, either can or cannot be a part of the optimal subset. There cannot be any other possibility for this book, right? This is what we are doing in this solution. We make two recursive calls: one with an object included (line 9), and another without (line 10). Then we take the maximum ...