01背包
二维
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
int n = sc.nextInt();
int[][] d = new int[n][2];
for(int i = 0; i<n; i++){
d[i][0] = sc.nextInt();
d[i][1] = sc.nextInt();
}
int[][] dp = new int[n+1][v+1];
for(int i = 1; i<= n ; i++){
for(int j = 1; j<= v; j++){
int val = d[i-1][1];
int wei = d[i-1][0];
if(j < wei){
//没用空间
dp[i][j] = dp[i-1][j];
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-wei]+val);
}
}
}
System.out.println(dp[n][v]);
}
}
一维(逆序)
状态转移中,i只和i-1有关系
所以这里更准确的是 滚动数组,而不是 降维
因为实际起作用的数组是一样的
但是需要逆序 不然就会被污染
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
int n = sc.nextInt();
int[] vals = new int[n];
int[] weis = new int[n];
for(int i = 0; i<n; i++){
weis[i] = sc.nextInt();
vals[i] = sc.nextInt();
}
int[] dp = new int[v+1];
for(int i =1; i<=n; i++){
for(int j=v; j>0 ; j--){
int val = vals[i-1];
int wei = weis[i-1];
if(j >= wei){
dp[j] = Math.max(dp[j],dp[j-wei]+val);
}
}
}
System.out.println(dp[v]);
}
}