#include <iostream>
#include <cstring>
#include<stdlib.h>
#define MAXN 1000
using namespace std;
int w[MAXN] = {0, 2, 1, 3, 2 };
int v[MAXN] = {0, 3, 2, 4, 2 };
int dp[MAXN][MAXN]; //记录搜索过的结果
int W = 5, n = 4;
int max(int a, int b) {
if (a>b)
return a;
else
return b;
}
int Rec(int i, int j) {
//Rec(i, j)计算过,直接拿来用
if (dp[i][j] != -1)
return dp[i][j];
int res=0;
if (i == 0) {
cout << res << " 1 " << i << " " << j << endl;
res = 0;
}
else if (j < w[i]) {
cout << res << " 2 " << i << " " << j << endl;
res = Rec(i - 1, j);
}
else {
cout << res << " 3 " << i << " " << j << endl;
res = max(Rec(i - 1, j), Rec(i - 1, j - w[i]) + v[i]);
}
return dp[i][j] = res; //记录
}
int main() {
memset(dp, -1, sizeof(dp));
cout << Rec(n, W) << endl;
system("pause");
return 0;
}
结果图:4 5之后是3 3。
即res = max(Rec(i - 1, j), Rec(i - 1, j - w[i]) + v[i]); 是先计算右边的。