我使用了动态规划。我把物品的体积和价格用数组固定死了,但也可以用Scanner输入的方式自己输入
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class 背包问题 {
public static void main(String[] args) {
int capacity = 15;
int[] vols = {1,2,3,7,5};
int[] prices = {1,1,2,15,12};
int maxPrice = backpack(capacity , vols , prices);
System.out.println(maxPrice);
}
public static int backpack(int capacity , int[] vols , int[] prices){
//体积与价值的对应
Map<Integer , Integer> vols_prices = new HashMap<>();
int i = 0 , j = 0;
//遍历体积与价值的数组将它们加入到map表中
for(i = 0 ; i < vols.length ;i++){
vols_prices.put(vols[i] , prices[i]);
}
//体积排序 从小到大
Arrays.sort(vols);
//动态规划数组
int[] dp = new int[capacity + 1];
dp[0] = 0;
for(i = 1 ; i <= capacity ;i++){
for (j = 0 ; j < vols.length ;j++){
//获取体积
int vol = vols[j];
if(vol > i){
break;
}
//获取体积对应得到价值
int price = vols_prices.get(vol);
dp[i] = Math.max(dp[(i-vol)] + price , dp[i]);
}
}
return dp[capacity];
}
}