1. Recursive Knapsack Search
Intuition
Recursively branch on how many boxes of each type to take (from 0 up to min(truckSize, boxes)), searching for the maximum total units.
Algorithm
- Step 1: Define recursive function solve(idx, remainingCapacity).
- Step 2: If idx == n or remainingCapacity == 0, return 0.
- Step 3: Try choosing k boxes where 0 <= k <= min(remainingCapacity, boxTypes[idx][0]).
- Step 4: Recurse on solve(idx + 1, remainingCapacity - k) + k * boxTypes[idx][1].
- Step 5: Return maximum across all choices.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int idx, int capacity, const vector<vector<int>>& boxTypes) { if (idx == boxTypes.size() || capacity <= 0) return 0; int maxUnits = 0; int maxTake = min(capacity, boxTypes[idx][0]); for (int k = 0; k <= maxTake; ++k) { int current = k * boxTypes[idx][1] + solve(idx + 1, capacity - k, boxTypes); maxUnits = max(maxUnits, current); } return maxUnits; }public: int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) { return solve(0, truckSize, boxTypes); }}; int main() { Solution sol; vector<vector<int>> boxTypes = {{1, 3}, {2, 2}, {3, 1}}; int truckSize = 4; cout << "Max Units: " << sol.maximumUnits(boxTypes, truckSize) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N)