二维:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
//输入物品个数N和背包容量V
int N = reader.nextInt();
int V = reader.nextInt();
//两个一维数组分别存储每个物品的体积与价值
int[] v = new int[N + 1];
int[] w = new int[N + 1];
for(int i = 1; i <= N; i++){
v[i] = reader.nextInt();
w[i] = reader.nextInt();
}
reader.close();
int[][] dp = new int[N + 1][V + 1];
dp[0][0] = 0;//第0个物品,体积为0时,最大价值为0
for(int i = 1; i <= N; i++){
for(int j = 0; j <= V; j++){
for(int k = 0; k * v[i] <= j; k++){
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
System.out.println(dp[N][V]);
}
}
一维:优化后
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
//输入物品个数N和背包容量V
int N = reader.nextInt();
int V = reader.nextInt();
//两个一维数组分别存储每个物品的体积与价值
int[] v = new int[N + 1];
int[] w = new int[N + 1];
for(int i = 1; i <= N; i++){
v[i] = reader.nextInt();
w[i] = reader.nextInt();
}
reader.close();
int[][] dp = new int[N + 1][V + 1];
dp[0][0] = 0;//第0个物品,体积为0时,最大价值为0
for(int i = 1; i <= N; i++){
for(int j = 0; j <= V; j++){
for(int k = 0; k * v[i] <= j; k++){
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
System.out.println(dp[N][V]);
}
}