所以,我试图从我们的教科书中实现这个算法。使用递归算法解决背包
我写了这个:
// Knapsack_memoryfunc.cpp : Defines the entry point for the console application.
//Solving Knapsack problem using dynamic programmig and Memory function
#include "stdafx.h"
#include "iostream"
#include "iomanip"
using namespace std;
int table[20][20] = { 0 };
int value, n, wt[20], val[20], max_wt;
// ---CONCERNED FUNCTION-----
int MNSack(int i, int j)
{
value = 0;
if (table[i][j] < 0)
if (j < wt[i])
value = MNSack(i - 1, j);
else
value = fmax(MNSack(i - 1, j), val[i] + MNSack(i - 1, j - wt[i]));
table[i][j] = value;
return table[i][j];
}
// --------------------------
void items_picked(int n, int max_wt)
{
cout << "\n Items picked : " << endl;
while (n > 0)
{
if (table[n][max_wt] == table[n - 1][max_wt]) // if value doesnot change in table column-wise, item isn't selected
n--; // n-- goes to next item
else // if it changes, it is selected
{
cout << " Item " << n << endl;
max_wt -= wt[n]; // removing weight from total available (max_wt)
n--; // next item
}
}
}
int main()
{
cout << " Enter the number of items : ";
cin >> n;
cout << " Enter the Maximum weight : ";
cin >> max_wt;
cout << endl;
for (int i = 1; i <= n; i++)
{
cout << " Enter weight and value of item " << i << " : ";
cin >> wt[i] >> val[i];
}
for (int i = 0; i <= n; i++)
for (int j = 0; j <= max_wt; j++)
table[i][j] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= max_wt; j++)
table[i][j] = -1;
cout << " Optimum value : " << MNSack(n, max_wt);
cout << " \n Table : \n";
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= max_wt; j++)
if (table[i][j] == -1)
cout << setw(5) << "-";
else
cout << setw(5) << table[i][j];
cout << endl;
}
items_picked(n, max_wt);
return 0;
}
好像它像最佳值有些地方是正确的,但不完全可接受。 我试图调试它,但它很难用递归函数。有人可以帮忙吗?
Heyho,我认为HenryLee的回答是正确的,但它仍然希望稍后给你一些东西。 Ur代码有点可怕,而你解决这个问题的方式在程序员之下被称为memoization。这是一个美丽的博客帖子,它帮助了我很多,可以让你的代码更加美丽。 http://programminggenin.blogspot.de/2013/01/memoization-in-c.html – Mehno
@Mehno你能详细说明吗?据我所知,算法只计算所需的值。我能更好地实现它吗? – LonelyC
@Mehno建议的是一种让您的编码风格更好的技术。算法中没有什么不好的。但是,如果您有兴趣,我可以告诉您如何使用自下而上的动态编程来解决同样的问题,这需要很少的行数,并且使代码更好。 – HenryLee