参考代码:
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int[][] dp = new int[n+1][m+1]; // [物品数目][背包空间] int[] ar = new int[n+1]; for (int i = 1; i <= n; i++) { ar[i] = sc.nextInt(); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (j >= ar[i]){ dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j - ar[i]] + ar[i]); }else { dp[i][j] = dp[i-1][j]; } } } System.out.println(m-dp[n][m]); } }
0.0分
1 人评分