1 /** 2 * @author: yekai <br/> 3 * Date: 2021/12/18:21:53 <br/> 4 * Description:动态规划-背包问题 5 * 解题思路: 6 * 1明确状态:背包的空余容量,可选择的物品 7 * 2明确转移 8 */ 9 public class main { 10 public static void main(String[] args) { 11 int N = 3; 12 int W = 4; 13 int[] val = {4, 2, 3}; 14 int[] wt = {2, 1, 3}; 15 int max = knapsnack(W, N, val, wt); 16 System.out.println(max); 17 } 18 19 private static int knapsnack(int W, int N, int[] val, int[] wt) { 20 //dp数组初始化:代表前N个物品中,空余容量在w下的最大价值 21 int[][] dp = new int[N + 1][W + 1]; 22 for (int i = 1; i <= N; i++) { 23 for (int w = 1; w <= W; w++) { 24 if (w - wt[i - 1] < 0) { 25 //放不进去了 26 dp[i][w] = dp[i - 1][w]; 27 } else { 28 dp[i][w] = Math.max( 29 //放进去:i的值加上i-1的最大价值 30 val[i - 1] + dp[i - 1][w - wt[i - 1]], 31 //不放进去 32 dp[i - 1][w] 33 ); 34 } 35 } 36 } 37 return dp[N][W]; 38 } 39 }