完全背包问题
function getMaxGold(n,w,g,p){
var nextGold,
results = [];
for(var i = 0; i <= w; i++){
results[i] = (i < p[0]) ? 0 : g[0];
}
for(var i = 0; i < n; i++){
for(var j = 0; j <= w; j++){
if(j >= p[i]){
nextGold = g[i] + results[j-p[i]];
results[j] = Math.max(results[j],nextGold);
}
}
console.log(results);
}
return results;
}
console.log(getMaxGold(5,10,[400,500,200,300,350],[5,5,3,4,3]));
01背包问题
function getMaxGold2(n,w,g,p){
var preResults = [],
results = [];
for(var i = 0; i <= w; i++){
preResults[i] = (i < p[0]) ? 0 : g[0];
}
for(var i = 1; i < n; i++){
for(var j = 0; j <= w; j++){
if(j < p[i]){
results[j] = preResults[j];
}else{
results[j] = Math.max(preResults[j],g[i] + preResults[j-p[i]]);
}
}
for(var k = 0 ; k <= w; k++){
preResults[k] = results[k];
}
}
return results;
}
// console.log(getMaxGold2(5,10,[400,500,200,300,350],[5,5,3,4,3]));
01背包问题
function getMaxGold3(n,w,g,p){
var nextGold,
results = [];
for(var i = 0; i <= w; i++){
results[i] = (i < p[0]) ? 0 : g[0];
}
for(var i = 1; i < n; i++){
for(var j = w; j >= 0; j--){
if(j >= p[i]){
nextGold = g[i] + results[j-p[i]];
// console.log(nextGold);
results[j] = Math.max(results[j],nextGold);
}
}
}
return results;
}
// console.log(getMaxGold3(5,10,[400,500,200,300,350],[5,5,3,4,3]));