0-1 Knapsack proble
1 package Three; 2 3 public class KNAPSACK { 4 public static int [][] KNAPSACK_DP(int[] v,int [] w,int W) 5 { 6 int n=w.length-1; 7 int[][] c=new int[n+1][W+1]; 8 for(int j=0;j<=W;j++) 9 { 10 c [0][j]=0; 11 } 12 for(int i=0;i<=n;i++) 13 { 14 c[i][0]=0; 15 } 16 for(int i=1;i<=n;i++){//前i个物品 17 for(int j=1;j<=W;j++) 18 { 19 //if(w[i]<=W) 20 //{ 21 if(w[i]<=j)//当前最大容量为j 22 { 23 if(v[i]+c[i-1][j-w[i]]>c[i-1][j]) 24 c[i][j]=v[i]+c[i-1][j-w[i]]; 25 else c[i][j]=c[i-1][j]; 26 } 27 //} 28 else c[i][j]=c[i-1][j]; 29 } 30 } 31 return c;//[n][W]; 32 } 33 public static void PrintArray(int [][] array,int W) 34 { 35 int n=array.length-1; 36 for(int i=1;i<=n;i++){ 37 for(int j=1;j<=W;j++){ 38 System.out.print(array[i][j]+" "); 39 } 40 System.out.println(); 41 } 42 System.out.println(); 43 System.out.println("the biggist value is "+array[n][W]); 44 45 } 46 public static void main(String[] args) 47 { 48 int [] weight={0,1,2,5,6,7};//考虑到28行有c[i-1],在前面添一个0元素 49 int [] value={0,1,6,18,22,28}; 50 int[][] c=KNAPSACK_DP(value,weight,11); 51 //System.out.println("the biggist value is "+v); 52 PrintArray(c,11); 53 } 54 55 }