我一直在尝试使用背包问题来解决特定的领域。给定一个约束:
我想从大约100,000个食谱的搜索空间中制定最佳的用餐计划。每个配方都是具有以下属性的对象:
public class Recipe {
private Integer id;
private String name;
private double calories;
}
如何使用背包问题来解决此问题?我一直在看here中的代码,而对如何实现约束感到困惑。
class Knapsack {
public static void main(String[] args) throws Exception {
int val[] = {10, 40, 30, 50};
int wt[] = {5, 4, 6, 3};
int W = 10;
System.out.println(knapsack(val, wt, W));
}
public static int knapsack(int val[], int wt[], int W) {
int N = wt.length;
int[][] V = new int[N + 1][W + 1];
for (int col = 0; col <= W; col++) {
V[0][col] = 0;
}
for (int row = 0; row <= N; row++) {
V[row][0] = 0;
}
for (int item=1;item<=N;item++){
for (int weight=1;weight<=W;weight++){
if (wt[item-1]<=weight){
V[item][weight]=Math.max (val[item-1]+V[item-1][weight-wt[item-1]], V[item-1][weight]);
}
else {
V[item][weight]=V[item-1][weight];
}
}
}
for (int[] rows : V) {
for (int col : rows) {
System.out.format("%5d", col);
}
System.out.println();
}
return V[N][W];
}
}