/**
- 给定
n
件物品,每一个物品的重量为w[n]
,每个物品的价值为v[n]
。现挑选物品放入背包中, - 假定背包能承受的最大重量为
capacity
,求装入物品的最大价值是多少?
*/
//数据(可以自己修改)(别忘了复制该部分)
public class Main {
static int[] weight = {2, 3, 4, 5};//weight
static int[] value = {3, 4, 5, 6};//value
static int capacity = 8;
public static void main(String[] args){
/*System.out.println(text_1(0,0));*/
text_2();
}
//回溯法(0/1,递归)
public static int text_1(int index,int currentWeight){//index为下一步索引,weight为当前重量
if(index >= 4)return 0;
if(currentWeight + weight[index] > capacity)return 0;
//返回最大价值
return Math.max(value[index]+text_1(index+1, currentWeight + weight[index]),text_1(index+1, currentWeight));//前一项表1,后一项表0
}
//动态规划(dp)
public static void text_2(){
//下定义的dp为在'该行该列'能装下的'最大''价值'行为物品数目,列为当前容量,加一是因为多加了以00为开头的一行一列,其元素值均为0
int[][] dp = new int[weight.length + 1][capacity + 1];//加上00行和列,weight.length为物品数目与value.length相当
for (int i = 1; i <= weight.length; i++) {//0行列以及默认为0,不用再写//此处表示行数,为当前可装入的物品编号
for (int j = 1; j <= capacity; j++) {//此处为列数,表示当前容量
//有两种情况:1.选择装入当前物品(当然,容量不足以装入时dp[][]为0即可,所以需要一次判断)(而且当容量有剩余时,需要加上剩余容量可以装下的最大价值)
//2.不装入当前物品,此时dp[i][j]==dp[i-1][j]
//之所以weight和value索引为0-1因为他们其实是从0开始的,而我们设定的i其实是多了一行全为0的元素
int Value_1 = (j - weight[i-1] >= 0) ? (value[i-1]+dp[i-1][j-weight[i-1]]) : 0;
int Value_2 = dp[i-1][j];
dp[i][j] = Math.max(Value_1,Value_2);
}
}
//展示构建的表格
for (int i = 0; i <= weight.length; i++) {
for (int j = 0; j <= capacity; j++)
System.out.print(dp[i][j]+" ");
System.out.println();
}
}
}