Top Down
int knapsack(int W, vector<int>& wt, vector<int>& val, int n, vector<vector<int>>& dp) {
if (n == 0 || W == 0) return 0;
if (dp[n][W] != -1) return dp[n][W];
if (wt[n-1] <= W)
return dp[n][W] = max(
val[n-1] + knapsack(W - wt[n-1], wt, val, n-1, dp),
knapsack(W, wt, val, n-1, dp)
);
else
return dp[n][W] = knapsack(W, wt, val, n-1, dp);
}
Bottom Up
int knapsackBU(int W, vector<int>& wt, vector<int>& val, int n) {
vector<vector<int>> dp(n+1, vector<int>(W+1, 0));
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (wt[i-1] <= w)
dp[i][w] = max(dp[i-1][w], val[i-1] + dp[i-1][w - wt[i-1]]);
else
dp[i][w] = dp[i-1][w];
}
}
return dp[n][W];
}
1. Bounded Knapsack (Limited Copies)
Each item has a limited count
k[i]
-
Approach: Expand each item
k[i]
times or use Binary Representation Decomposition for optimization. - ♾️ 2. Unbounded Knapsack
-
Can use an item any number of times.
-
Change: Inner loop runs
for (int w = wt[i]; w <= W; w++)
. - 🎯 3. Exact Weight Knapsack
-
Find the max value such that total weight = W exactly.
-
Change: Initialize
dp[0] = 0
, rest to-∞
. Only update when a solution to that weight is possible. - 🎒 4. Multiple Constraints (e.g., Weight + Volume)
-
Each item has weight and volume, and the bag has max weight
W
and volumeV
. -
Approach: 3D DP table
dp[i][w][v]
. - 🎲 5. Knapsack with Item Dependencies
-
Some items can only be picked if their "parent" is picked (tree-like structure).
-
Approach: DP on tree / post-order traversal + state memoization.
- 🎯 6. Meet-in-the-Middle Knapsack (n ≤ 40)
-
Brute-force both halves and combine smartly.
-
Used when
n
is too big for standardO(nW)
DP. - 🧾 7. Count Number of Ways to Fill Knapsack to Capacity
-
Count how many distinct combinations of items give total weight
W
. -
Change: Replace
max()
with+
in DP transitions. - 🔒 8. Knapsack with Forbidden Pairs
-
Some item pairs cannot be taken together.
-
Approach: Add constraints in state transition or prune combinations.
Comments
Post a Comment