Given weights and profits of N items, put these items in a knapsack of capacity W. The task is to print all possible solutions to the problem in such a way that there are no remaining items left whose weight is less than the remaining capacity of the knapsack. Also, compute the maximum profit.
Examples: 
Input: Profits[] = {60, 100, 120, 50}
Weights[] = {10, 20, 30, 40}, W = 40
Output:
10: 60, 20: 100,
10: 60, 30: 120,
Maximum Profit = 180
Explanation:
Maximum profit from all the possible solutions is 180Input: Profits[] = {60, 100, 120, 50}
Weights[] = {10, 20, 30, 40}, W = 50
Output:
10: 60, 20: 100,
10: 60, 30: 120,
20: 100, 30: 120,
Maximum Profit = 220
Explanation:
Maximum profit from all the possible solutions is 220
Approach: The idea is to make pairs for the weight and the profits of the items and then try out all permutations of the array and including the weights until their is no such item whose weight is less than the remaining capacity of the knapsack. Meanwhile after including an item increment the profit for that solution by the profit of that item.
Below is the implementation of the above approach:
C++
| // C++ implementation to print all// the possible solutions of the// 0/1 Knapsack problem#include <bits/stdc++.h>usingnamespacestd;// Utility function to find the// maximum of the two elementsintmax(inta, intb) {     return(a > b) ? a : b; }// Function to find the all the// possible solutions of the // 0/1 knapSack problemintknapSack(intW, vector<int> wt,             vector<int> val, intn){    // Mapping weights with Profits    map<int, int> umap;        set<vector<pair<int, int>>> set_sol;    // Making Pairs and inserting    // into the map    for(inti = 0; i < n; i++) {        umap.insert({ wt[i], val[i] });    }    intresult = INT_MIN;    intremaining_weight;    intsum = 0;        // Loop to iterate over all the     // possible permutations of array    do{        sum = 0;                // Initially bag will be empty        remaining_weight = W;        vector<pair<int, int>> possible;                // Loop to fill up the bag         // until there is no weight        // such which is less than        // remaining weight of the        // 0-1 knapSack        for(inti = 0; i < n; i++) {            if(wt[i] <= remaining_weight) {                remaining_weight -= wt[i];                autoitr = umap.find(wt[i]);                sum += (itr->second);                possible.push_back({itr->first,                     itr->second                });            }        }        sort(possible.begin(), possible.end());        if(sum > result) {            result = sum;        }        if(set_sol.find(possible) ==                         set_sol.end()){            for(autosol: possible){                cout << sol.first << ": "                     << sol.second << ", ";            }            cout << endl;            set_sol.insert(possible);        }            } while(        next_permutation(wt.begin(),                            wt.end()));    returnresult;}// Driver Codeintmain(){    vector<int> val{ 60, 100, 120 };    vector<int> wt{ 10, 20, 30 };    intW = 50;    intn = val.size();    intmaximum = knapSack(W, wt, val, n);    cout << "Maximum Profit = ";    cout << maximum;    return0;} | 
Java
| // Java implementation to print all// the possible solutions of the// 0/1 Knapsack problemimportjava.util.*;publicclassMain {    // Utility function to find the maximum of the two    // elements    staticintmax(inta, intb) { return(a > b) ? a : b; }    // Function to find the all the possible solutions of    // the 0/1 knapSack problem    staticintknapSack(intW, List<Integer> wt,                        List<Integer> val, intn)    {        // Mapping weights with Profits        Map<Integer, Integer> umap = newHashMap<>();        Set<List<Map.Entry<Integer, Integer> > > setSol            = newHashSet<>();        // Making Pairs and inserting into the map        for(inti = 0; i < n; i++) {            umap.put(wt.get(i), val.get(i));        }        intresult = Integer.MIN_VALUE;        intremaining_weight;        intsum = 0;        // Loop to iterate over all the possible        // permutations of array        do{            sum = 0;            // Initially bag will be empty            remaining_weight = W;            List<Map.Entry<Integer, Integer> > possible                = newArrayList<>();            // Loop to fill up the bag until there is no            // weight such which is less than remaining            // weight of the 0-1 knapSack            for(inti = 0; i < n; i++) {                if(wt.get(i) <= remaining_weight) {                    remaining_weight -= wt.get(i);                    Integer valAtWtI = umap.get(wt.get(i));                    sum += valAtWtI;                    possible.add(                        newAbstractMap.SimpleEntry<>(                            wt.get(i), valAtWtI));                }            }            Collections.sort(                possible,                Comparator.comparingInt(Map.Entry::getKey));            if(sum > result) {                result = sum;            }            if(!setSol.contains(possible)) {                for(Map.Entry<Integer, Integer> sol :                     possible) {                    System.out.print(sol.getKey() + ": "                                     + sol.getValue()                                     + ", ");                }                System.out.println();                setSol.add(possible);            }        } while(nextPermutation(wt));        returnresult;    }    // Utility function to generate the next permutation    staticbooleannextPermutation(List<Integer> arr)    {        inti = arr.size() - 2;        while(i >= 0&& arr.get(i) >= arr.get(i + 1)) {            i--;        }        if(i < 0) {            returnfalse;        }        intj = arr.size() - 1;        while(arr.get(j) <= arr.get(i)) {            j--;        }        inttemp = arr.get(i);        arr.set(i, arr.get(j));        arr.set(j, temp);        Collections.reverse(arr.subList(i + 1, arr.size()));        returntrue;    }    // Driver code    publicstaticvoidmain(String[] args)    {        List<Integer> val            = newArrayList<>(Arrays.asList(60, 100, 120));        List<Integer> wt            = newArrayList<>(Arrays.asList(10, 20, 30));        intW = 50;        intn = val.size();        intmaximum = knapSack(W, wt, val, n);        System.out.println("Maximum Profit = "+ maximum);    }}// This code was contributed by rutikbhosale | 
Python3
| # Python3 implementation to print all# the possible solutions of the# 0/1 Knapsack problemINT_MIN=-2147483648defnextPermutation(nums: list) -> None:        """        Do not return anything, modify nums in-place instead.        """        ifsorted(nums,reverse=True)==nums:            returnNone        n=len(nums)        brk_point=-1        forpos inrange(n-1,0,-1):            ifnums[pos]>nums[pos-1]:                brk_point=pos                break        else:            nums.sort()            return        replace_with=-1        forj inrange(brk_point,n):            ifnums[j]>nums[brk_point-1]:                replace_with=j            else:                break        nums[replace_with],nums[brk_point-1]=nums[brk_point-1],nums[replace_with]        nums[brk_point:]=sorted(nums[brk_point:])        returnnums# Function to find the all the# possible solutions of the # 0/1 knapSack problemdefknapSack(W, wt, val, n):    # Mapping weights with Profits    umap=dict()        set_sol=set()    # Making Pairs and inserting    # o the map    fori inrange(n) :        umap[wt[i]]=val[i]        result =INT_MIN    remaining_weight=0    sum=0        # Loop to iterate over all the     # possible permutations of array    whileTrue:        sum=0                # Initially bag will be empty        remaining_weight =W        possible=[]                # Loop to fill up the bag         # until there is no weight        # such which is less than        # remaining weight of the        # 0-1 knapSack        fori inrange(n) :            if(wt[i] <=remaining_weight) :                remaining_weight -=wt[i]                sum+=(umap[wt[i]])                possible.append((wt[i],                     umap[wt[i]])                )                            possible.sort()        if(sum> result) :            result =sum                if(tuple(possible) notinset_sol):            forsol inpossible:                print(sol[0], ": ", sol[1], ", ",end='')                        print()            set_sol.add(tuple(possible))                        ifnotnextPermutation(wt):            break    returnresult# Driver Codeif__name__ =='__main__':    val=[60, 100, 120]     wt=[10, 20, 30]     W =50    n =len(val)    maximum =knapSack(W, wt, val, n)    print("Maximum Profit =",maximum)#This code was contributed by Amartya Ghosh | 
Javascript
| // Utility function to find the maximum of the two elementsfunctionmax(a, b) {     return(a > b) ? a : b; }// Function to find the all the possible solutions of the 0/1 knapSack problemfunctionknapSack(W, wt, val, n) {    // Mapping weights with Profits    let umap = newMap();    let set_sol = newSet();    // Making Pairs and inserting into the map    for(let i = 0; i < n; i++) {        umap.set(wt[i], val[i]);    }    let result = Number.MIN_SAFE_INTEGER;    let remaining_weight, sum;        // Loop to iterate over all the possible permutations of array    do{        sum = 0;                // Initially bag will be empty        remaining_weight = W;        let possible = [];                // Loop to fill up the bag until there is no weight such which is less than remaining weight of the 0-1 knapSack        for(let i = 0; i < n; i++) {            if(wt[i] <= remaining_weight) {                remaining_weight -= wt[i];                let val = umap.get(wt[i]);                sum += val;                possible.push([wt[i], val]);            }        }                possible.sort((a, b) => a[0] - b[0]);                if(sum > result) {            result = sum;        }                if(!set_sol.has(JSON.stringify(possible))) {            for(let i = 0; i < possible.length; i++) {                console.log(possible[i][0] + ": "+ possible[i][1] + ", ");            }                        console.log();            set_sol.add(JSON.stringify(possible));        }    } while(nextPermutation(wt));    returnresult;}// Function to generate the next permutation of arrayfunctionnextPermutation(a) {    let i = a.length - 2;    while(i >= 0 && a[i] >= a[i + 1]) {        i--;    }    if(i < 0) {        returnfalse;    }    let j = a.length - 1;    while(a[j] <= a[i]) {        j--;    }    let temp = a[i];    a[i] = a[j];    a[j] = temp;    for(let l = i + 1, r = a.length - 1; l < r; l++, r--) {        temp = a[l];        a[l] = a[r];        a[r] = temp;    }    returntrue;}// Driver Codefunctionmain() {    let val = [60, 100, 120];    let wt = [10, 20, 30];    let W = 50;    let n = val.length;    let maximum = knapSack(W, wt, val, n);    console.log("Maximum Profit = "+ maximum);}main(); | 
C#
| usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classMainClass {    // Utility function to find the maximum of the two elements    staticintmax(inta, intb) { return(a > b) ? a : b; }    // Function to find the all the possible solutions of    // the 0/1 knapSack problem    staticintknapSack(intW, List<int> wt,                        List<int> val, intn)    {        // Mapping weights with Profits        Dictionary<int, int> umap = newDictionary<int, int>();        HashSet<List<KeyValuePair<int, int>>> setSol            = newHashSet<List<KeyValuePair<int, int>>>();        // Making Pairs and inserting into the map        for(inti = 0; i < n; i++) {            umap.Add(wt[i], val[i]);        }        intresult = int.MinValue;        intremaining_weight;        intsum = 0;        // Loop to iterate over all the possible permutations of array        do{            sum = 0;            // Initially bag will be empty            remaining_weight = W;            List<KeyValuePair<int, int>> possible                = newList<KeyValuePair<int, int>>();            // Loop to fill up the bag until there is no            // weight such which is less than remaining            // weight of the 0-1 knapSack            for(inti = 0; i < n; i++) {                if(wt[i] <= remaining_weight) {                    remaining_weight -= wt[i];                    intvalAtWtI = umap[wt[i]];                    sum += valAtWtI;                    possible.Add(                        newKeyValuePair<int, int>(                            wt[i], valAtWtI));                }            }            possible.Sort(                (x, y) => x.Key.CompareTo(y.Key));            if(sum > result) {                result = sum;            }            if(!setSol.Contains(possible)) {                foreach(KeyValuePair<int, int> sol inpossible) {                    Console.Write(sol.Key + ": "+ sol.Value                                     + ", ");                }                Console.WriteLine();                setSol.Add(possible);            }        } while(nextPermutation(wt));        returnresult;    }    // Utility function to generate the next permutation    staticboolnextPermutation(List<int> arr)    {        inti = arr.Count - 2;        while(i >= 0 && arr[i] >= arr[i + 1]) {            i--;        }        if(i < 0) {            returnfalse;        }        intj = arr.Count - 1;        while(arr[j] <= arr[i]) {            j--;        }        inttemp = arr[i];        arr[i] = arr[j];        arr[j] = temp;        arr.Reverse(i + 1, arr.Count - i - 1);        returntrue;    }    // Driver code    publicstaticvoidMain(string[] args)    {        List<int> val = newList<int>{60, 100, 120};        List<int> wt = newList<int>{10, 20, 30};        intW = 50;        intn = val.Count;        intmaximum = knapSack(W, wt, val, n);        Console.WriteLine("Maximum Profit = "+ maximum);    }} | 
10: 60, 20: 100, 10: 60, 30: 120, 20: 100, 30: 120, Maximum Profit = 220
Time complexity : O(N! * N), where N is the number of items. The code uses permutation to generate all possible combinations of items and then performs a search operation to find the optimal solution.
Space complexity : O(N), as the code uses a map and set to store the solution, which has a maximum size of N.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







