publicclassZeroOnePack { /** * @param N count of things * @param W bag capcity * @param wt weight of i-th thing * @param val value of i-th thing * @return */ publicintknapsack(int N, int W, int[] wt, int[] val) { int[][] dp = newint[N + 1][W + 1];
for (intn=1; n <= N; n++) { for (intw=1; w <= W; w++) { // not suitable if (w - wt[n - 1] < 0) { dp[n][w] = dp[n - 1][w]; } else { dp[n][w] = Math.max(dp[n - 1][w], dp[n - 1][w - wt[n - 1]] + val[n - 1]); } } }
return dp[N][W]; }
/** * Just the same as the method above, and just change the names of parameters to make it easier to understand. * * @param thingsNum * @param bagCapcity * @param wtArr * @param valArr * @return */ publicintanotherKnapsack(int thingsNum, int bagCapcity, int[] wtArr, int[] valArr) { int[][] dp = newint[thingsNum + 1][bagCapcity + 1];
for (intn=1; n <= thingsNum; n++) { for (intc=1; c <= bagCapcity; c++) { if (c - wtArr[n - 1] < 0) { dp[n][c] = dp[n - 1][c]; } else { dp[n][c] = Math.max(dp[n - 1][c], dp[n - 1][c - wtArr[n - 1]] + valArr[n - 1]); } } }