C++ Knapsack Problem recursive implementation


👍 g++ -std=c++11 knapsack_rec.cpp
👍 ./a.out
24
👍 cat knapsack_rec.cpp 
#include <iostream>
using namespace std;

typedef struct 
  { int size; int val; } Item;
Item A{3,  4}, B{4,  5}, C{7, 10},
     D{8, 11}, E{9, 13};
Item itms[]{A, B, C, D, E};

int N = 5;

int knap(int cap) {
  int i, sp, max, t;
  for (i = 0, max = 0; i < N; i++)
    if((sp=cap-itms[i].size)>=0)
      if((t=knap(sp)+itms[i].val)>max)
        max = t;
  return max;
}
    
int main() {
  cout << knap(17) << endl;
}

    

ch5.3 Dynamic Programming p248/227 of