我正在解决背包问题,但我无法进行完整搜索。这是代码:
public class Backpack {
static int maxWeight = 80;
Goods[] goods;
public static void main(String[] args) {
Goods[] goods = {
new Goods(15, 30),
new Goods(30, 90),
new Goods(50, 100)
};
System.out.println("Total: " + findBestRes(goods));
}
private static int findBestRes(Goods[] goods){
int max = 0;
for (int i = 0; i < goods.length; i++) {
int temp = goods[i].getValue();
maxWeight -= goods[i].getWeight();
for (int j = 0; j < goods.length; j++) {
if (i != j && maxWeight >= goods[j].getWeight()){
temp += goods[j].getValue();
maxWeight -= goods[j].getWeight();
}
}
if (temp > max) {
max = temp;
}
maxWeight = 80;
}
return max;
}
}
public class Goods {
private int weight;
private int value;
public Goods(int weight, int value){
this.weight = weight;
this.value = value;
}
public int getWeight() {
return weight;
}
public int getValue() {
return value;
}
}
不要告诉我如何正确实现它或者是否有必要在这里重做所有事情?
好吧,让我们按顺序去吧。