让我们定义函数 f(i,j),它给出从前 i+1 个项目 (0,1...i) 中选择项目的最小成本,其中这些项目的权重之和正好等于j,那么至少获得权重(minW=15)的最小成本将这样计算:
min(f(i,j)) where i=0,1...n-1, j=minW,minW+1,.... maxW
- n is the number of items
- minW=15 in your case
- maxW is the maximum possible sum of all the given weights
你可以参考这段C++代码(非常类似于Java):
const int maxW = 100;//the maximum weight, a problem constraint
const int maxN = 100;//the maximum number of items, a problem constraint
int n = 6; //input
int w[maxN] = { 1, 1, 1, 5, 13, 3 };//the weights(should be read as an input)
int c[maxN] = { 1, 1, 1, 5, 10, 12 };//the costs(should be read as an input)
int f[maxN][maxW];
for (int i = 0; i < maxN; i++)
for (int j = 0; j < maxW; j++)
f[i][j] = 1000000;//some big value
int minW = 15;//the minimum weight(should be read as an input)
int result = 1000000;
f[0][w[0]] = c[0];//initialization
for (int i = 1; i < n; i++) {
for (int j = 0; j < maxW; j++) {
f[i][j] = f[i - 1][j];//don't pick the i-th item
if (j - w[i] >= 0) {//pick the i-th item if possible
if (f[i][j] > f[i - 1][j - w[i]] + c[i])
f[i][j] = f[i - 1][j - w[i]] + c[i];
}
if (j >= minW and f[i][j] < result) {
result = f[i][j];//store the minimum cost when the weight is >= minW
}
}
}
cout << result << endl;//print the result(12 in this case)