动态规划(背包问题)
public class BagProblem {
public static void main(String[] arg){
//背包承受的重量
final int MAX_WEIGHT = 8;
final int MIN_WEIGHT = 1;
//value决定当前的价值
int[] value = new int[MAX_WEIGHT+1];
//item记录选的是谁
int[] item = new int[MAX_WEIGHT+1];
FruitInBag[] FruitInBags = {
new FruitInBag("李子",4,4500),new FruitInBag("苹果",5,5700),
new FruitInBag("橘子",2,2250),new FruitInBag("草莓",1,1100),new FruitInBag("甜瓜",6,6700)};
for(int i = 0;i<FruitInBags.length;i++){
//j为当前背包的重量
for(int j = FruitInBags[i].getWeight();j<=MAX_WEIGHT;j++){
//剩余空间
int p = j - FruitInBags[i].getWeight();
int newValue = FruitInBags[i].getPrice()+value[p];
if(newValue >value[j]){
value[j] = newValue;
item[j] = i;
}
}
}
for(int i:item){
System.out.print(i);
}
}
}
class FruitInBag {
private String name;
private int weight;
private int price;
public FruitInBag(String name,int weight,int price){
this.name = name;
this.price = price;
this.weight = weight;
}
public String getName(){
return this.name;
}
public int getWeight(){
return this.weight;
}
public int getPrice(){
return this.price;
}
}