01背包问题及其拓展
求背包的最大价值,并求其由哪些物品组成(拓展)
//01背包问题 public class Main{ static int m = 8; static int n = 4; static int[] value = { 0 , 3 , 4 , 5 , 6 }; static int[] weight = { 0 , 2 , 3 , 4 , 5 }; static int[][] dp = new int[n+1][m+1]; static int[] item = new int[5]; public static void main(String[] args) { findMax(); System.out.println("-------------"); findWhat(4,8); print(); System.out.println("-------------"); print2(); } //最优解 static void findMax(){ for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (j >= weight[i]){ int a = dp[i-1][j]; int b = dp[i-1][j-weight[i]]+value[i]; dp[i][j] = a > b ? a : b; } else{ dp[i][j] = dp[i-1][j]; } } } System.out.println(dp[n][m]); } //最优解组成回溯 static void findWhat(int i, int j) { //最优解情况 if (i > 0) { if (dp[i][j] == dp[i - 1][j]) { item[i] = 0; findWhat(i - 1, j); } else if (j - weight[i] >= 0 && dp[i][j] == dp[i - 1][j - weight[i]] + value[i]) { item[i] = 1; findWhat(i - 1, j - weight[i]); } } } //最优解二维表打印 static void print(){ int count = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 9; j++) { System.out.print(dp[i][j]+" "); count++; if (count==9){ count = 0; System.out.println(); } } } } //背包由哪些物品组成 1代表有该物品,0代表没有该物品 static void print2(){ int count = 0; for (int i = 0; i < n+1; i++) { System.out.println(item[i]); } } }
输出结果:
参考博客:https://blog.csdn.net/qq_38410730/article/details/81667885
https://blog.csdn.net/lanyu_01/article/details/79815801
如果对背包问题求解思路和如何填表仍有疑问的同学,推荐看这一篇文章: