一、动态规划法
这有一篇讲的很好:http://blog.csdn.net/livelylittlefish/article/details/2186206#
JAVA仿写的例子:
public class Test {
//背包中150
//七个物品
//物品 A B C D E F G
//重量 35 30 60 50 40 10 25
//价值 10 40 30 50 35 40 30
private int[] weight=new int[]{0,35,30,60,50,40,10,25};
private int[] value =new int[]{0,10,40,30,50,35,40,30};
private int[] check=new int[8];
//保存动态的结果
public int getMaxValue(int n,int m,int[] weight,int[] value,int[]check){
int maxValue=0;
int row=n+1;
int col=m+1;
//保存结果
int[][] result=new int[row][col];
for(int i=1;i<row;i++)
for(int j=1;j<col;j++){
result[i][j]=result[i-1][j];
if(weight[i]<=j){
//这儿很关键
int temp=result[i-1][j-weight[i]]+value[i];
if(temp>result[i-1][j])
result[i][j]=temp;
}
// if(weight[i]<=j){
// int temp=result[i-1][j-weight[i]]+value[i];
// if(temp>result[i-1][j])
// result[i][j]=temp;
// else{
// result[i][j]=result[i-1][j];
// }
// }else{
// result[i][j]=result[i-1][j];
// }
//
maxValue=maxValue>result[i][j]?maxValue:result[i][j];
}
int l=m;
for(int k=row-1;k>0;k--){
if(result[k][l]>result[k-1][l]){
check[k]=1;
l-=weight[k];
}
}
System.out.println(Arrays.toString(check));
return maxValue;
}
public int testResult(){
return getMaxValue(7, 150, weight, value,check);
}
public static void main(String[] args) {
Test t=new Test();
System.out.println(t.testResult());
//System.out.println(-10>>3);
}
}
二、贪心算法
我现在对看到的理解是 1.首先对处理的实物要排序
2.就是当前感觉的最好结果
三、参考
http://www.cnblogs.com/chinazhangjie/archive/2010/11/23/1885330.html