Kaidul

Nafee

Oct 16th, 2014
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.55 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3.  
  4. using namespace std;
  5.  
  6. int arr[] = {5, 10, 7, 6, 4, 20}, n = 6, target = 25;
  7.  
  8. int knapsack(int indx, int sum) {
  9.     if(sum > target) {
  10.         return sum;
  11.     }
  12.     if(indx == n) {
  13.         if(sum <= target) {
  14.             return INT_MAX;
  15.         }
  16.         return sum;
  17.     }
  18.     int ret1 = knapsack(indx + 1, sum + arr[indx]);
  19.     int ret2 = knapsack(indx + 1, sum);
  20.     return min(ret1, ret2);
  21. }
  22.  
  23. int main() {
  24.     sort(arr, arr +n); // if the array isn't already sorted
  25.     cout << knapsack(0, 0);
  26.     return 0;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment