0/1 Knapsack Problem to print all possible solutions
Last Updated :
03 Apr, 2023
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>
using namespace std;
// Utility function to find the
// maximum of the two elements
int max(int a, int b) {
return (a > b) ? a : b;
}
// Function to find the all the
// possible solutions of the
// 0/1 knapSack problem
int knapSack(int W, vector<int> wt,
vector<int> val, int n)
{
// Mapping weights with Profits
map<int, int> umap;
set<vector<pair<int, int>>> set_sol;
// Making Pairs and inserting
// into the map
for (int i = 0; i < n; i++) {
umap.insert({ wt[i], val[i] });
}
int result = INT_MIN;
int remaining_weight;
int sum = 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 (int i = 0; i < n; i++) {
if (wt[i] <= remaining_weight) {
remaining_weight -= wt[i];
auto itr = 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 (auto sol: possible){
cout << sol.first << ": "
<< sol.second << ", ";
}
cout << endl;
set_sol.insert(possible);
}
} while (
next_permutation(wt.begin(),
wt.end()));
return result;
}
// Driver Code
int main()
{
vector<int> val{ 60, 100, 120 };
vector<int> wt{ 10, 20, 30 };
int W = 50;
int n = val.size();
int maximum = knapSack(W, wt, val, n);
cout << "Maximum Profit = ";
cout << maximum;
return 0;
}
Java
// Java implementation to print all
// the possible solutions of the
// 0/1 Knapsack problem
import java.util.*;
public class Main {
// Utility function to find the maximum of the two
// elements
static int max(int a, int b) { return (a > b) ? a : b; }
// Function to find the all the possible solutions of
// the 0/1 knapSack problem
static int knapSack(int W, List<Integer> wt,
List<Integer> val, int n)
{
// Mapping weights with Profits
Map<Integer, Integer> umap = new HashMap<>();
Set<List<Map.Entry<Integer, Integer> > > setSol
= new HashSet<>();
// Making Pairs and inserting into the map
for (int i = 0; i < n; i++) {
umap.put(wt.get(i), val.get(i));
}
int result = Integer.MIN_VALUE;
int remaining_weight;
int sum = 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
= new ArrayList<>();
// Loop to fill up the bag until there is no
// weight such which is less than remaining
// weight of the 0-1 knapSack
for (int i = 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(
new AbstractMap.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));
return result;
}
// Utility function to generate the next permutation
static boolean nextPermutation(List<Integer> arr)
{
int i = arr.size() - 2;
while (i >= 0 && arr.get(i) >= arr.get(i + 1)) {
i--;
}
if (i < 0) {
return false;
}
int j = arr.size() - 1;
while (arr.get(j) <= arr.get(i)) {
j--;
}
int temp = arr.get(i);
arr.set(i, arr.get(j));
arr.set(j, temp);
Collections.reverse(arr.subList(i + 1, arr.size()));
return true;
}
// Driver code
public static void main(String[] args)
{
List<Integer> val
= new ArrayList<>(Arrays.asList(60, 100, 120));
List<Integer> wt
= new ArrayList<>(Arrays.asList(10, 20, 30));
int W = 50;
int n = val.size();
int maximum = 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 problem
INT_MIN=-2147483648
def nextPermutation(nums: list) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if sorted(nums,reverse=True)==nums:
return None
n=len(nums)
brk_point=-1
for pos in range(n-1,0,-1):
if nums[pos]>nums[pos-1]:
brk_point=pos
break
else:
nums.sort()
return
replace_with=-1
for j in range(brk_point,n):
if nums[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:])
return nums
# Function to find the all the
# possible solutions of the
# 0/1 knapSack problem
def knapSack(W, wt, val, n):
# Mapping weights with Profits
umap=dict()
set_sol=set()
# Making Pairs and inserting
# o the map
for i in range(n) :
umap[wt[i]]=val[i]
result = INT_MIN
remaining_weight=0
sum = 0
# Loop to iterate over all the
# possible permutations of array
while True:
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
for i in range(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) not in set_sol):
for sol in possible:
print(sol[0], ": ", sol[1], ", ",end='')
print()
set_sol.add(tuple(possible))
if not nextPermutation(wt):
break
return result
# Driver Code
if __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 elements
function max(a, b) {
return (a > b) ? a : b;
}
// Function to find the all the possible solutions of the 0/1 knapSack problem
function knapSack(W, wt, val, n) {
// Mapping weights with Profits
let umap = new Map();
let set_sol = new Set();
// 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));
return result;
}
// Function to generate the next permutation of array
function nextPermutation(a) {
let i = a.length - 2;
while (i >= 0 && a[i] >= a[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
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;
}
return true;
}
// Driver Code
function main() {
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#
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
// Utility function to find the maximum of the two elements
static int max(int a, int b) { return (a > b) ? a : b; }
// Function to find the all the possible solutions of
// the 0/1 knapSack problem
static int knapSack(int W, List<int> wt,
List<int> val, int n)
{
// Mapping weights with Profits
Dictionary<int, int> umap = new Dictionary<int, int>();
HashSet<List<KeyValuePair<int, int>>> setSol
= new HashSet<List<KeyValuePair<int, int>>>();
// Making Pairs and inserting into the map
for (int i = 0; i < n; i++) {
umap.Add(wt[i], val[i]);
}
int result = int.MinValue;
int remaining_weight;
int sum = 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
= new List<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 (int i = 0; i < n; i++) {
if (wt[i] <= remaining_weight) {
remaining_weight -= wt[i];
int valAtWtI = umap[wt[i]];
sum += valAtWtI;
possible.Add(
new KeyValuePair<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 in possible) {
Console.Write(sol.Key + ": " + sol.Value
+ ", ");
}
Console.WriteLine();
setSol.Add(possible);
}
} while (nextPermutation(wt));
return result;
}
// Utility function to generate the next permutation
static bool nextPermutation(List<int> arr)
{
int i = arr.Count - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
int j = arr.Count - 1;
while (arr[j] <= arr[i]) {
j--;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
arr.Reverse(i + 1, arr.Count - i - 1);
return true;
}
// Driver code
public static void Main(string[] args)
{
List<int> val = new List<int>{60, 100, 120};
List<int> wt = new List<int>{10, 20, 30};
int W = 50;
int n = val.Count;
int maximum = knapSack(W, wt, val, n);
Console.WriteLine("Maximum Profit = " + maximum);
}
}
Output10: 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.
Similar Reads
Introduction to Knapsack Problem, its Types and How to solve them The Knapsack problem is an example of the combinational optimization problem. This problem is also commonly known as the "Rucksack Problem". The name of the problem is defined from the maximization problem as mentioned below:Given a bag with maximum weight capacity of W and a set of items, each havi
6 min read
Fractional Knapsack
0/1 Knapsack
0/1 Knapsack ProblemGiven n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Printing Items in 0/1 KnapsackGiven weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
12 min read
0/1 Knapsack Problem to print all possible solutionsGiven 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.Exampl
10 min read
0-1 knapsack queriesGiven an integer array W[] consisting of weights of the items and some queries consisting of capacity C of knapsack, for each query find maximum weight we can put in the knapsack. Value of C doesn't exceed a certain integer C_MAX. Examples: Input: W[] = {3, 8, 9} q = {11, 10, 4} Output: 11 9 3 If C
12 min read
0/1 Knapsack using Branch and BoundGiven two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity W.Note: The constraint here is we can either put
15+ min read
0/1 Knapsack using Least Cost Branch and BoundGiven N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that:Â Â The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations.Examples:Â Â Input:
15+ min read
Unbounded Fractional Knapsack Given the weights and values of n items, the task is to put these items in a knapsack of capacity W to get the maximum total value in the knapsack, we can repeatedly put the same item and we can also put a fraction of an item. Examples: Input: val[] = {14, 27, 44, 19}, wt[] = {6, 7, 9, 8}, W = 50 Ou
5 min read
Unbounded Knapsack (Repetition of items allowed) Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
15+ min read
Unbounded Knapsack (Repetition of items allowed) | Efficient Approach Given an integer W, arrays val[] and wt[], where val[i] and wt[i] are the values and weights of the ith item, the task is to calculate the maximum value that can be obtained using weights not exceeding W. Note: Each weight can be included multiple times. Examples: Input: W = 4, val[] = {6, 18}, wt[]
8 min read
Double Knapsack | Dynamic Programming Given an array arr[] containing the weight of 'n' distinct items, and two knapsacks that can withstand capactiy1 and capacity2 weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e. an item
15+ min read
Some Problems of Knapsack problem
Partition a Set into Two Subsets of Equal SumGiven an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both.Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: Th
15+ min read
Count of subsets with sum equal to targetGiven an array arr[] of length n and an integer target, the task is to find the number of subsets with a sum equal to target.Examples: Input: arr[] = [1, 2, 3, 3], target = 6 Output: 3 Explanation: All the possible subsets are [1, 2, 3], [1, 2, 3] and [3, 3]Input: arr[] = [1, 1, 1, 1], target = 1 Ou
15+ min read
Length of longest subset consisting of A 0s and B 1s from an array of stringsGiven an array arr[] consisting of binary strings, and two integers a and b, the task is to find the length of the longest subset consisting of at most a 0s and b 1s.Examples:Input: arr[] = ["1" ,"0" ,"0001" ,"10" ,"111001"], a = 5, b = 3Output: 4Explanation: One possible way is to select the subset
15+ min read
Breaking an Integer to get Maximum ProductGiven a number n, the task is to break n in such a way that multiplication of its parts is maximized. Input : n = 10Output: 36Explanation: 10 = 4 + 3 + 3 and 4 * 3 * 3 = 36 is the maximum possible product. Input: n = 8Output: 18Explanation: 8 = 2 + 3 + 3 and 2 * 3 * 3 = 18 is the maximum possible pr
15+ min read
Coin Change - Minimum Coins to Make SumGiven an array of coins[] of size n and a target value sum, where coins[i] represent the coins of different denominations. You have an infinite supply of each of the coins. The task is to find the minimum number of coins required to make the given value sum. If it is not possible to form the sum usi
15+ min read
Coin Change - Count Ways to Make SumGiven an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
Maximum sum of values of N items in 0-1 Knapsack by reducing weight of at most K items in halfGiven weights and values of N items and the capacity W of the knapsack. Also given that the weight of at most K items can be changed to half of its original weight. The task is to find the maximum sum of values of N items that can be obtained such that the sum of weights of items in knapsack does no
15+ min read