Solution: The 0/1 Knapsack Problem
This review provides a detailed analysis of the different ways to solve the knapsack problem.
We'll cover the following...
Solution 1: brute force
Explanation
We start from the beginning of the weight list and check if the item is within the maximum capacity on line 20.
For each item starting from the end:
- create a new set which INCLUDES item ‘i’ if the total weight does not exceed the capacity
and recursively process the remaining capacity and items. Save the result in
profit1(line 20). - create a new set WITHOUT item ‘i’, recursively process the remaining items, and save the result in the variable,
profit2(line 23).
Return the set from the above two sets with higher profit (line 28).
Let’s draw the recursive calls to see if there are any overlapping subproblems. As we can see, in each recursive call, the profits and weights lists remain constant and only the capacity and the current index change. For simplicity, let’s denote capacity with j and current index with n:
Time complexity
The time complexity of the algorithm above is —i.e., exponential—where is the total number of items. This is because we will have that many calls. This is owing to the overlapping subproblems. Let’s see how we can reduce it with a dynamic programming approach.
Solution 2: top-down dynamic programming approach with memoization
Explanation
The function knap_sack ...