1.0-1背包
import java.util.*; public class Main{ public static void main(String[] args) { int N=5; int max=10; int[] weights={2,2,6,5,4}; int[] values={6,3,5,4,6}; int[] c=new int[max+1]; c[0]=0; for(int i=0;i<N;i++){ for(int j=max;j>0;j--){ if(weights[i]<=j){ c[j]=Math.max(c[j],c[j-weights[i]]+values[i]); }else{ c[j]=c[j]; } } } System.out.println(c[max]); } }
2.完全背包
import java.util.*; public class Main{ public static void main(String[] args) { int N=5; int max=10; int[] weights={2,2,6,5,4}; int[] values={4,3,5,4,6}; int[] c=new int[max+1]; c[0]=0; for(int i=0;i<N;i++){ for(int j=max;j>0;j--){ int count=max/weights[i]; for(int k=0;k<=count;k++){ if(weights[i]*k<=j){ c[j]=Math.max(c[j],c[j-weights[i]*k]+values[i]*k); } } } } System.out.println(c[max]); } }
3.多重背包
import java.util.*; public class Main{ public static void main(String[] args) { int N=5; int max=10; int[] weights={2,2,6,5,4}; int[] values={4,3,5,4,6}; int[] counts={2,3,1,2,3}; int[] c=new int[max+1]; c[0]=0; for(int i=0;i<N;i++){ for(int j=max;j>0;j--){ for(int k=0;k<=counts[i];k++){ if(weights[i]*k<=j){ c[j]=Math.max(c[j],c[j-weights[i]*k]+values[i]*k); } } } } System.out.println(c[max]); } }