0-1背包问题

//动态规划求解背包问题
public
class Dynamic{ static int[] weight = new int[]{2, 2, 4, 6, 3}; static int n = 5; static int m = 9; static int maxW = 0; public static void dynamic(){ boolean[][] result = new boolean[n][m + 1]; result[0][0] = true; result[0][weight[0]] = true;
  
for(int i = 1; i < n; i++){
    //不装入背包
for(int j = 0; j <= m; j++){ if(result[i - 1][j] == true){ result[i][j] = true; } }
    //装入背包
for(int j = 0; j <= m - weight[i]; j++){ if(result[i - 1][j] == true){ result[i][j + weight[i]] = true; } } } print_result(result); } public static void print_result(boolean[][] result){ for(int i = 0; i < n; i++){ for(int j = 0; j < m + 1; j++){ if(result[i][j] == true){ System.out.print("1 "); } else{ System.out.print("* "); } } System.out.println(); } } public static void main(String[] argv){ dynamic(); } }

 

输出结果:

1 * 1 * * * * * * *
1 * 1 * 1 * * * * *
1 * 1 * 1 * 1 * 1 *
1 * 1 * 1 * 1 * 1 *
1 * 1 1 1 1 1 1 1 1

 

回溯算法:

// 回溯算法实现
private int maxW = Integer.MIN_VALUE; // 结果放到 maxW 中
private int[] weight = {2,2,4,6,3};  // 物品重量
private int n = 5; // 物品个数
private int w = 9; // 背包承受的最大重量
public void f(int i, int cw) { // 调用 f(0, 0)
  if (cw == w || i == n) { // cw==w 表示装满了,i==n 表示物品都考察完了
    if (cw > maxW) maxW = cw;
    return;
  }
  f(i+1, cw); // 选择不装第 i 个物品
  if (cw + weight[i] <= w) {
    f(i+1,cw + weight[i]); // 选择装第 i 个物品
  }
}

 

posted @ 2019-05-23 17:12  小时候挺菜  阅读(285)  评论(0编辑  收藏  举报