编辑代码

package dynamicprogramming;
import java.util.Arrays;
import java.util.LinkedList;


public class Backpack {

     public static LinkedList<place> stealObject(int packCapacity, place[] items) {
        // 1. 找出子问题,确定表格的行和列
        int rowCount = items.length + 1;
        int colCount = packCapacity + 1;
        // 2. 构建存储子问题的表格
        int[][] dpArray = new int[rowCount][colCount];
        LinkedList<place> objectStolen = new LinkedList<place>(); // 记录需要偷的东西

        //表格清零
        for (int i = 0; i < rowCount; ++i) {
            Arrays.fill(dpArray[i], 0);
        }

        //3. 利用公式(Max(item[i - 1].value + Cell[i-1][j - item[i-1].weight], Cell[i-1][j]))填充动态规划表
        for (int i = 1; i < rowCount; ++i) {
            for (int j = 1; j < colCount; ++j) {
                
                if (items[i-1].days <= j){
                    // 当前行对应的物品可以放入背包
                    dpArray[i][j] = Math.max(items[i-1].scores + dpArray[i - 1][j - items[i-1].days], dpArray[i-1][j]);
                }
                else {
                    // 当前行对应的物品不可以放入背包
                    dpArray[i][j] = dpArray[i-1][j];
                }
                
            }
        }

        //4. 利用表格找出要放入包中的物品
        int i = rowCount - 1;
        int j = colCount - 1;
        while(i > 0 && j > 0) {

            if (dpArray[i][j] != dpArray[i-1][j]) {
                // 当前行对应的物品被放入包包
                objectStolen.addFirst(items[i-1]);
                j = j - items[i-1].days; // 减去放入包的当前物品的重量
                i = i-1; // 去掉当前物品
            }
            else {
                // 当前行对应的物品不被放入包包
                i = i - 1;// 去掉当前物品
            }
        }

        return objectStolen;
    }
	public static void test() {
        place[] items = {
                new place("故宫", 7, 1),
                new place("颐和园", 8, 2),
                new place("长城", 9, 3),
                new place("天坛", 6, 1)
        };

        LinkedList<place> objectInPack = stealObject(4, items);

        int maxValue = 0;

        System.out.println("景点能够获得最大价值:");
        for (place item : objectInPack) {
            maxValue += item.scores;
            System.out.println(item.name);
        }

        System.out.println("总评分:" + maxValue);

	}

    public static void main(String[] args) {
        Backpack.test();
    }
}
class place {
    public String name;
    public int scores;
    public int days;

    public place(String n, int s, int d) {
        this.name = n;
        this.scores = s;
        this.days = d;
    }
}