我想知道是否有任何针对背包问题的具体问题和答案,我可以输入并修改此代码,以确保我做得正确?我试图进入动态编程并开始解决这个问题,但是没有办法知道它是否在没有输入的情况下工作 - 我在一些功率点上发现了一些情况,而我的代码输出了正确的信息,是非常基本和简单的案例,所以我想确保这更加丰富的输入。
这是我的代码:
import java.util.ArrayList;
public class Knapsack {
private int numThings = 0;
public static void main(String[] args) {
(new Knapsack()).run();
}
public void run() {
ArrayList<Thing> thingList = new ArrayList<Thing>();
thingList.add(new Thing(60, 2));
thingList.add(new Thing(75, 3));
thingList.add(new Thing(90, 4));
int maxWeight = 5;
int[] vals = new int[maxWeight + 1];
vals[2] = 60;
Thing nullThing = new Thing(0,0);
Thing max;
int maxSet = 0;
for (int i = 1; i < vals.length; i++) {// lets go through weights leading up to our maximal weight
System.out.println(i);
max = nullThing;
for (Thing x : thingList) {
if ((i-x.getWeight() >= 0) && (x.getValue() + vals[i-x.getWeight()] > max.getValue() + vals[i-max.getWeight()])) {
max = x;
maxSet = 1;//here, we compare possibilities of adding items by subtracting weights from our current index and seeing which ones produce the highest values
}
}
if (maxSet == 1) {
vals[i] = max.getValue() + vals[i-max.getWeight()];
System.out.println(max.info() );//if we find something that sets a highest value, we cache that info into the array for future use
}
}
System.out.println(vals[maxWeight]);
}
private class Thing {
private int value, weight;
public Thing(int v, int w) {
value = v;
weight = w;
}
public int getValue() {
return value;
}
public int getWeight() {
return weight;
}
public String info() {
return "I have a weight of "+weight+" and a value of "+ value;
}
}
}