01背包二维dp数组:
public class BeiBao {
public static void main(String[] args) {
int[] weight = {1, 3, 4};
int[] value = {15, 20, 30};
int bagWeight = 4;
int[][] dp = new int[weight.length + 1][bagWeight + 1];
for(int i = 1; i <= weight.length; i++){
for(int j = 1; j <= bagWeight; j++){
if(j < weight[i - 1]){
dp[i][j] = dp[i - 1][j];
}else{
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i - 1]] + value[i - 1]);
}
}
}
System.out.println(dp[weight.length][bagWeight]);
}
}
完全背包二维dp数组
public class WanQuanBeiBao {
public static void main(String[] args) {
int[] weight = {1, 3, 4};
int[] value = {15, 20, 30};
int bagWeight = 4;
int[][] dp = new int[weight.length + 1][bagWeight + 1];//从前 i 个物品里任意取,放入背包容量为 j 的背包中,可以得到的最大价值是 dp[i][j]
for(int i = 1; i <= weight.length; i++){
for(int j = 1; j <= bagWeight; j++){
if(j < weight[i - 1]){
dp[i][j] = dp[i - 1][j];
}else{
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - weight[i - 1]] + value[i - 1]);
}
}
}
System.out.println(dp[weight.length][bagWeight]);
}
}
01背包一维dp数组:
public class BeiBao {
public static void main(String[] args) {
int[] weight = {1, 3, 4};
int[] value = {15, 20, 30};
int bagWeight = 4;
int[] dp = new int[bagWeight + 1];
dp[0] = 0;
for(int i = 0; i < weight.length; i++){
for(int j = bagWeight; j >= 0; j--){//每一个元素一定是不可重复放入,所以从大到小遍历
if(j >= weight[i]){
dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
}
}
}
System.out.println(dp[bagWeight]);
}
}
完全背包一维dp数组:
public class WanQuanBeiBao {
public static void main(String[] args) {
int[] weight = {1, 3, 4};
int[] value = {15, 20, 30};
int bagWeight = 4;
int[] dp = new int[bagWeight + 1];
for(int i = 0; i < weight.length; i++){//遍历物品
for(int j = 0; j <= bagWeight; j++){//遍历背包容量
if(j >= weight[i]){
dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
}
}
}
System.out.println(dp[bagWeight]);
}
}
注:一维dp都是根据二维dp写出来的。
为什么在一维dp中,01背包要从后向前遍历?
因为要满足每个物品只能被选取一次;而完全背包一维dp就要从前向后遍历,因为每个物品可以被无限次选取。
那么为什么在一维dp中,两者的递推公式是一样的呢?
其实它里面代表的含义是不一样的,01背包中,因为是从后向前遍历,导致dp[j]前面的元素还没有被更新,也就是前面的dp[j - weight[i]]里面还存储的是上一层的元素,对应二维dp里面的dp[i - 1][j - weight[i - 1]];而完全背包中则不是,因为它是从前向后遍历,前面的元素已经被更新了,也就是前面的dp[j - weight[i]]里面存储的已经是这一层的元素,对应二维dp里的dp[i][j - weight[i - 1]]。但两者等式右边的dp[j]代表的都是上一层的元素,即二维dp中的dp[i - 1][j]