1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| package leetcode.problems.medium;
import util.PrintUtil;
public class BackPackII {
public int backPackII(int m, int[] A, int[] V) { int itemNum = A.length; int weight[] = A; int value[] = V; if (itemNum == 0 || m == 0) return 0; int[][] dp = new int[itemNum][m + 1]; for (int i = 0; i < dp.length; i++) { dp[i][0] = 0; } for (int j = 0; j < m + 1; j++) { if (j < weight[0]) { dp[0][j] = 0; } else { dp[0][j] = value[0]; } }
for (int i = 1; i < itemNum; i++) { for (int j = 0; j <= m; j++) { if (weight[i] > j) { dp[i][j] = dp[i - 1][j]; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } } PrintUtil.printSubList(dp); return dp[itemNum-1][m]; }
public int backPackII1(int m, int[] A, int[] V) { int itemNum = A.length; int weight[] = A; int value[] = V; if (itemNum == 0 || m == 0) return 0; int[] dp = new int[m + 1]; for (int j = 0; j < m + 1; j++) { if (j < weight[0]) { dp[j] = 0; } else { dp[j] = value[0]; } } for (int i = 1; i < itemNum; i++) { for (int j = m; j >= weight[i]; j--) { dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); } } PrintUtil.printSubList(dp); return dp[m]; } }
|