Advertisement
193030

Knapsack recursive

May 8th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.55 KB | None | 0 0
  1. #include<fstream>
  2. #include <vector>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. vector <int> v{0,5,3,5,3,2};
  7.  
  8.  
  9.  
  10. //53532
  11.  
  12. int result = 0;
  13. int KnapSack(int n, int capacity)
  14. {
  15.     if((n==0)  || (capacity==0))
  16.         return 0;
  17.     else if(v.at(n) > capacity)
  18.         result = KnapSack(n-1, capacity);
  19.     else {
  20.         int temp1 = KnapSack(n-1,capacity);
  21.         int temp2 = v.at(n)+ KnapSack(n-1,capacity-v.at(n));
  22.         result = max(temp1, temp2);
  23.     }
  24.     return result;
  25.  
  26. }
  27.  
  28. int main(){
  29.     int res = KnapSack(5,23);
  30.     cout <<res;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement