2025-01-25 动态规划算法-背包问题
This commit is contained in:
parent
c563c48a4f
commit
3b53efd9a0
69
src/dataANDcalc/java/algorithm/Backpack.java
Normal file
69
src/dataANDcalc/java/algorithm/Backpack.java
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
package algorithm;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 背包问题-动态规划算法
|
||||||
|
*/
|
||||||
|
public class Backpack {
|
||||||
|
|
||||||
|
private int[] weight;
|
||||||
|
|
||||||
|
private int[] value;
|
||||||
|
|
||||||
|
private int[][] backpack;
|
||||||
|
|
||||||
|
private int capacity;
|
||||||
|
|
||||||
|
private int goodsNum;
|
||||||
|
|
||||||
|
private Map<Integer, String> goodsMap;
|
||||||
|
|
||||||
|
public Backpack(int capacity) {
|
||||||
|
weight = new int[4];
|
||||||
|
value = new int[4];
|
||||||
|
goodsNum = 1;
|
||||||
|
backpack = new int[4][capacity+1];
|
||||||
|
goodsMap = new HashMap<>();
|
||||||
|
this.capacity = capacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addPack(String name, int weight, int value){
|
||||||
|
goodsMap.put(goodsNum, name);
|
||||||
|
this.weight[goodsNum] = weight;
|
||||||
|
this.value[goodsNum] = value;
|
||||||
|
for (int j = 1; j <= capacity; j++) {
|
||||||
|
if (this.weight[goodsNum] > j){
|
||||||
|
// 如果当前物品超重,则取前一个物品对应当前容量的价值
|
||||||
|
backpack[goodsNum][j] = backpack[goodsNum-1][j];
|
||||||
|
} else {
|
||||||
|
// 如果当前物品没有超重,则取前一个物品对应当前容量的价值 和 当前物品价值加上减去当前物品重量后的前面物品对应重量的价值之和 的最大值
|
||||||
|
backpack[goodsNum][j] = Math.max(backpack[goodsNum - 1][j],backpack[goodsNum - 1][j - this.weight[goodsNum]] + this.value[goodsNum]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
goodsNum ++;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getMaxValue(){
|
||||||
|
return backpack[goodsNum-1][capacity];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void showPack(){
|
||||||
|
for (int i = 0; i < goodsNum; i++) {
|
||||||
|
for (int j = 0; j < capacity+1; j++) {
|
||||||
|
System.out.print(backpack[i][j] + " ");
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Backpack backpack = new Backpack(4);
|
||||||
|
backpack.addPack("吉他",1,1500);
|
||||||
|
backpack.addPack("音响",4,3000);
|
||||||
|
backpack.addPack("电脑",3,2000);
|
||||||
|
backpack.showPack();
|
||||||
|
System.out.println("背包的最大价值为:" + backpack.getMaxValue());
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user