1. Recursive Exhaustive Search (Include/Exclude)
Intuition
For each item from 0 to N-1, branch into two decisions: take the item if wt[i] <= W, or skip it. Return the maximum value obtained from both branches.
Algorithm
- Define helper function
solve(i, remainingW). - Base Case: If
i == NorremainingW == 0, return 0. - If
wt[i] > remainingW, we cannot include item i; returnsolve(i + 1, remainingW). - Otherwise, compute
take = val[i] + solve(i + 1, remainingW - wt[i])andnotTake = solve(i + 1, remainingW). - Return
max(take, notTake).
#include <iostream>#include <vector>#include <algorithm> using namespace std; int knapsackRecursive(int i, int W, const vector<int>& wt, const vector<int>& val) { if (i == (int)wt.size() || W == 0) return 0; if (wt[i] > W) { return knapsackRecursive(i + 1, W, wt, val); } int take = val[i] + knapsackRecursive(i + 1, W - wt[i], wt, val); int notTake = knapsackRecursive(i + 1, W, wt, val); return max(take, notTake);} int main() { vector<int> val = {60, 100, 120}; vector<int> wt = {10, 20, 30}; int W = 50; cout << "Max Knapsack Value: " << knapsackRecursive(0, W, wt, val) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N) - Space complexity:
O(N) recursion stack space