function memset(array, v) {
    for (var i = 0, n = array.length; i < n; i++) {
        array[i] = v;
    }
}
var N = 3; //物品个数
var W = 5; //最大容量
var weights = [3, 2, 2]; //物品重量
var values = [5, 10, 20]; //物品价值
var dp = new Array(5 + 1);
var G = [];

function knapsack() {
    memset(dp, 0);
    for (var i = 0; i <= N; i++) {
        for (var j = W; j >= weights[i]; j--) {
            if (dp[j] < dp[j - weights[i]] + values[i]) {
                dp[j] = dp[j - weights[i]] + values[i];
                if (!G[i]) {
                    G[i] = [];
                }
                G[i][j] = 1;
            }
        }
    }
    console.log(dp, G);
    return dp[W];
}
function PrintKnapsack_recursion(i, j) {
    if (i == 0 || j == 0) {
        return;
    }
    if (G[i][j] == 1) {
        PrintKnapsack_recursion(i - 1, j - weights[i]);
        console.log(i);
    }
}
var a = knapsack();
console.log(a);

function PrintKnapsack() {
    var i = N - 1; //枚举物品
    var j = W - 1; //枚举空间

    console.log("加入背包的物品编号:");
    while (i) {
        if (G[i][j] == 1) {
            /*if不满足，表示第i件物品没装入背包,  
               if条件满足，表示放入背包了*/

            console.log(i);
            j -= weights[i]; //此时容量减少
        }
        i--;
    }
}
PrintKnapsack();
