从01背包学习贪心算法和动态规划

https://img-blog.csdn.net/20150501212932504

``````package DP;

import java.awt.*;
import java.util.Scanner;

public class bagdp {
static final int NIF = 9999;
static int N;//背包数目
static int[] worth;//单个物品价值
static int[] cap;//单个物品容量
static int[][] values;//存放价值，也是自上而下求解问题的必备数据结构
static int maxVal;//最大价值
public static void main(String[] args){
Scanner in = new Scanner(System.in);
maxVal = in.nextInt();
N = in.nextInt();
worth = new int[N+1];
cap = new int[N+1];
values = new int[N+1][maxVal+1];
for(int i = 1;i <= N;i++){
worth[i] = in.nextInt();
cap[i] = in.nextInt();
}
for(int i = 0;i <= N;i++)
for(int j = 0;j <= maxVal;j++)
values[i][j] = NIF;
for(int i = 0;i <= N;i++)
values[i][0] = 0;
for(int i = 0;i <= maxVal;i++)
values[0][i] = 0;
//System.out.print("可装最大价值为："+greedy(N,maxVal)+"\n");
System.out.print("可装最大价值为："+greedy2()+"\n");
printBags();

in.close();
}
public static int greedy(int i,int j){//贪心算法
if(values[i][j] < NIF) return values[i][j];//备忘录
if(j < cap[i]) values[i][j] = greedy(i-1,j);//容不下就不要了
if(j >= cap[i]){//可以容得下
values[i][j] = max(greedy(i-1,j),greedy(i-1,j-cap[i])+worth[i]);
}
return values[i][j];
}

public static int greedy2(){//动态规划算法，自下而上
for(int i = 1;i <= N;i++)
for(int j = 1;j <= maxVal;j++)
{
if(j < cap[i]) values[i][j] = values[i-1][j];
else if(j >= cap[i]){
values[i][j] = max(values[i-1][j],values[i-1][j-cap[i]]+worth[i]);
}
}
return values[N][maxVal];
}

public static int max(int a,int b){
return a>b?a:b;
}

public static void printBags(){//回溯打印选择的背包
int j = maxVal;
for(int i = N;i > 0;i--){
if(values[i][j] > values[i-1][j]){
System.out.print("背包"+i+"  ");
j = j -cap[i];
if(j < 0) break;
}
}
}
}
greedy是贪心算法（采用了备忘录自上而下的思想），greedy2则采用动态规划思想。``````