What is 0/1 Knapsack
Each item is taken once or not at all. A 1D table dp[cap] holds the best value for that capacity. Walking capacity downward after each item guarantees the item is not reused in the same pass.
dp[cap-w] + value.Brute force approach
2^n subsets. Correct, but the hidden tests go to n = 200.Each item is taken or skipped once. The state is (item index, capacity left). Brute force recomputes that pair. Memoization stores it.
At most 3 items, written as value weight pairs, and capacity up to 8. Default 3 2, 4 3, 5 4 with capacity 5 is worth 7. The practice case 60 10, 100 20, 120 30 with W = 50 is too wide for a full tree.
Memoized approach
dp[cap] = max(skip, take) walking capacity downward so an item is used at most once. Time O(nW).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each (item, cap) | O(1) |
| Fill table | O(nW) |
| Space | O(W) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations