Given a set of different items, each one with an associated value and weight, determine which items you should pick in order to maximize the value of the items without surpassing the capacity of your backpack.
#include
#include
// a function that solves the backpack problem using dynamic programming
int backpack(int capacity, std::vector<int> weights, std::vector<int> values) {
// create a 2D array to store the results of subproblems
int n = weights.size();
int dp[n + 1][capacity + 1];
// solve all subproblems
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= capacity; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (weights[i - 1] <= w)
dp[i][w] = std::max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
// cout the dp table
std::cout << "\n The dp table is:" << std::endl;
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= capacity; ++j) {
std::cout << dp[i][j] << " ";
}
std::cout << std::endl;
}
// the answer is in the bottom right corner of the table
return dp[n][capacity];
}
int test_backpack() {
std::vector<int> weights = { 2, 3, 4, 5 };
std::vector<int> values = { 3, 4, 5, 6 };
int capacity = 8;
std::cout << "The maximum value of items that fit into the backpack is " << backpack(capacity, weights, values) << std::endl;
return 0;
}
int main() {
test_backpack();
return 0;
}
#include
#include
// define a fucntion that handle the backpack problem with recursion
int backpack(int i, int j, std::vector<int> &w, std::vector<int> &v) {
if (i == 0) {
return 0;
}
if (j < w[i]) {
return backpack(i - 1, j, w, v);
}
return std::max(backpack(i - 1, j, w, v), backpack(i - 1, j - w[i], w, v) + v[i]);
}
int test_backpack() {
std::vector<int> w = {2, 3, 4, 5};
std::vector<int> v = {3, 4, 5, 6};
int i = 3;
int j = 8;
std::cout << backpack(i, j, w, v) << std::endl;
return 0;
}
int main() {
test_backpack();
return 0;
}
#include
#include
// define a fucntion that handle the backpack problem with backtracking
int backpack(int i, int w, const std::vector<int>& weight, const std::vector<int>& value, std::vector<int>& x, int& maxvalue)
{
if (i >= weight.size())
{
int totalvalue = 0;
for (int j = 0; j < x.size(); ++j)
{
totalvalue += x[j] * value[j];
}
if (totalvalue > maxvalue)
{
maxvalue = totalvalue;
}
return 0;
}
if (w >= weight[i])
{
x[i] = 1;
backpack(i + 1, w - weight[i], weight, value, x, maxvalue);
}
x[i] = 0;
backpack(i + 1, w, weight, value, x, maxvalue);
return 0;
}
int test_backpack()
{
std::vector<int> weight = { 2, 2, 6, 5, 4 };
std::vector<int> value = { 6, 3, 5, 4, 6 };
std::vector<int> x(weight.size(), 0);
int maxvalue = 0;
backpack(0, 10, weight, value, x, maxvalue);
std::cout << "maxvalue: " << maxvalue << std::endl;
return 0;
}
int main()
{
test_backpack();
return 0;
}