所以,我試圖從我們的教科書中實現這個算法。使用遞歸算法解決揹包
我寫了這個:
// 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