01背包
01背包(二维数组)
for(int i = 1; i <= m ; i++){
for(int j = 1; j <= n; j++){
if(j <= w[i]){
dp[i][j] = dp[i-1][j];
}else{
dp[i][j] = max(dp[i-1][j], dp[i-1][j-w[i]]+c[i]);
}
}
01背包(一维数组)(优化)
for(int i = 1; i <= n ; i++){
for(int j = m; j >= w[i]; j--){
dp[j] = max(dp[j], dp[j-w[i]]+c[i]);
}
}
完全背包
完全背包(二维数组)
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
dp[i][j] = dp[i-1][j];
if(j >= w[i]){
dp[i][j] = max(dp[i][j], dp[i][j-w[i]]+c[i]);
}
}
}
完全背包(一维数组)(优化版)
for(int i = 1; i <= n; i++){
for(int j = w[i]; j <= m; j++){
dp[j] = max(dp[j], dp[j-w[i]]+c[i]);
}
}
多重背包
转换为01背包(容易超时)
for(int i = 1; i <= n; i++){
for(int k = 1; k <= s[i]; k++){
for(int j = m; j >= w[i]; j--){
dp[j] = max(dp[j], dp[j-w[i]]+c[i]);
}
}
}