| 12
 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
 
 | 
 
 
 public class GoldMining {
 
 
 
 
 
 
 
 
 public static int getBestGoldMiningV3(int w, int[] p, int[] g) {
 
 int[] results = new int[w + 1];
 
 for (int i = 1; i <= g.length; i++) {
 for (int j = w; j >= 1; j--) {
 if (j >= p[i - 1]) {
 results[j] = Math.max(results[j], results[j - p[i - 1]] + g[i - 1]);
 }
 }
 }
 
 return results[w];
 }
 
 
 
 
 
 
 
 
 public static int getBestGoldMiningV2(int w, int[] p, int[] g) {
 
 int[][] resultTable = new int[g.length + 1][w + 1];
 
 for (int i = 1; i <= g.length; i++) {
 for (int j = 1; j <= w; j++) {
 if (j < p[i - 1]) {
 resultTable[i][j] = resultTable[i - 1][j];
 } else {
 resultTable[i][j] = Math.max(resultTable[i - 1][j], resultTable[i - 1][j - p[i - 1]] + g[i - 1]);
 }
 }
 }
 
 return resultTable[g.length][w];
 }
 
 
 
 
 
 
 
 
 
 public static int getBestGoldMining(int w, int n, int[] p, int[] g) {
 if (w == 0 || n == 0) {
 return 0;
 }
 if (w < p[n - 1]) {
 return getBestGoldMining(w, n - 1, p, g);
 }
 return Math.max(getBestGoldMining(w, n - 1, p, g), getBestGoldMining(w - p[n - 1], n - 1, p, g) + g[n - 1]);
 }
 
 
 public static void main(String[] args) {
 int w = 10;
 int[] p = {5, 5, 3, 4, 3};
 int[] g = {400, 500, 200, 300, 350};
 System.out.println("最优收益:" + getBestGoldMining(w, g.length, p, g));
 System.out.println("最优收益:" + getBestGoldMiningV2(w, p, g));
 System.out.println("最优收益:" + getBestGoldMiningV3(w, p, g));
 }
 
 }
 
 |