1. Recursive Branching
Intuition
Recursively try taking each item that fits in the remaining capacity, branching into infinite combinations.
Algorithm
- Define
solve(remW). - If
remW <= 0, return 0. - Initialize
maxVal = 0. - For each item
ifrom 0 ton - 1: - If
wt[i] <= remW: -
maxVal = max(maxVal, val[i] + solve(remW - wt[i])). - Return
maxVal.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int remW, int n, const vector<int>& val, const vector<int>& wt) { if (remW <= 0) return 0; int maxVal = 0; for (int i = 0; i < n; ++i) { if (wt[i] <= remW) { maxVal = max(maxVal, val[i] + solve(remW - wt[i], n, val, wt)); } } return maxVal; }public: int knapSack(int n, int w, vector<int>& val, vector<int>& wt) { return solve(w, n, val, wt); }}; int main() { Solution sol; vector<int> val = {10, 40, 50, 70}; vector<int> wt = {1, 3, 4, 5}; cout << "Max Knapsack Value: " << sol.knapSack(4, 8, val, wt) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(n^w) - Space complexity:
O(w) call stack