AlgoDesign

Knapsack problem

1from functools import lru_cache
2class Solution:
3    def knapsackProblem(self, items, capacity):
4        return self.topDown(self, items, capacity, 0, 0)
5    
6    @lru_cache(None)
7    def topDown(self, items, capacity, i, c):
8        if i == len(items): return 0
9        if c >= capacity: return 0
10        comb1, comb2 = 0, 0
11        if c + items[i][0] <= capacity and i + 1 <= len(items): comb1 = items[i][1] + self.topDown(items, capacity, i + 1, c + items[i][0])
12        if i + 1 <= len(items): comb2 = self.topDown(items, capacity, i + 1, c)
13        return max(comb1, comb2)