时间效率空间效率都是O(nW),n是物品个数,W是背包重量
采用自顶向下,它只对必要的子问题求解并且只解一次。
import java.util.ArrayList;
public class MFKnapsack {
private int n;
private int W;
private int[] Weights;
private int[] Values;
private int[][] V;
public ArrayList<Integer> list;
public MFKnapsack(int n, int[] weights, int[] values, int w) {
super();
this.n = n;
this.Weights = weights;
this.Values = values;
this.W = w;
this.list = new ArrayList<Integer>();
V = new int[n + 1][w + 1];
for (int i = 0; i < n + 1; i++)
for (int j = 0; j < w + 1; j++) {
if (i == 0 || j == 0)
V[i][j] = 0;
else
V[i][j] = -1;
}
}
// 注意和算法描述时数组边界不同
public int mfknapsack(int i, int j) {
int value = 0;
if (V[i][j] < 0) {
if (j < Weights[i - 1]) {
value = mfknapsack(i - 1, j);
} else {
int v1 = mfknapsack(i - 1, j);
int v2 = Values[i - 1] + mfknapsack(i - 1, j - Weights[i - 1]);
value = (v1 > v2) ? v1 : v2;
}
V[i][j] = value;
}
return V[i][j];
}
public void showV() {
for (int i = 0; i < this.n + 1; i++) {
for (int j = 0; j < this.W + 1; j++)
System.out.print(V[i][j] + " ");
System.out.println();
}
}
public void findnapsack(int i, int j) {
if (i != 0) {
if (V[i][j] != V[i - 1][j])
{
list.add(i);
findnapsack(i - 1, j - Weights[i - 1]);
}
else {
findnapsack(i-1, j);
}
}
}
public static void main(String[] argv) {
int n = 4;
int w = 5;
int[] values = new int[] { 12, 10, 20, 15 };
int[] weights = new int[] { 2, 1, 3, 2 };
MFKnapsack mfk = new MFKnapsack(n, weights, values, w);
System.out.println(mfk.mfknapsack(n, w));
mfk.showV();
mfk.findnapsack(n, w);
System.out.println(mfk.list);
}
}