美文网首页
0/1背包问题

0/1背包问题

作者: 晚上吃火锅吗 | 来源:发表于2018-04-02 12:10 被阅读0次
public class beibao01 {

    public static void main(String[] args) {
        int n = 3;   //物品数量
        int m = 10; //背包容量
        int[] w = {3,4,5}; //物品重量
        int[] p = {4,5,6}; //=物品价值
        int[][] c = getPackage(n, m, w, p);
        for(int i =0; i<m+1;i++) {
            System.out.print(i + " ");
        }
        System.out.println();
        for(int i = 1; i<n+1; i++) {
            System.out.print(i + " ");
            for(int j=1; j<m+1; j++) {
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }

    }
    
    public static int[][] getPackage(int n, int m, int[] w, int[] p){
        int[][] c = new int[n+1][m+1];
        
        for(int i = 0; i < m+1; i++) {
            c[0][i] = 0;
        }
        for(int j = 0; j<n+1; j++) {
            c[j][0] = 0;
        }
        
        for(int i = 1; i <= n; i++) {
            for (int j =1; j <= m; j++) {
                if(w[i - 1] <= j) {
                    if(c[i-1][j] < c[i-1][j - w[i-1]]+p[i-1]) {
                        c[i][j] = c[i-1][j - w[i-1]]+p[i-1];
                    }else {
                        c[i][j] = c[i-1][j];
                    }
                }else {
                    c[i][j] = c[i-1][j];
                }
            }
        }       
        return c;
    }
}

输出结果

0 1 2 3 4 5 6 7 8 9 10 
1 0 0 4 4 4 4 4 4 4 4 
2 0 0 4 5 5 5 9 9 9 9 
3 0 0 4 5 6 6 9 10 11 11 

相关文章

  • Algorithm进阶计划 -- 动态规划(下)

    经典动态规划背包问题最长子序列问题 1. 背包问题 1.1 0-1 背包问题 0-1 背包问题,描述如下: 上面...

  • 背包问题

    背包问题属于典型的动态规划问题。这里我们将详细介绍0-1背包,完全背包和多重背包问题 一、 0-1背包 有N件物品...

  • 算法-动态规划-背包问题

    背包问题是基础的动态规划问题,包含了0-1背包,完全背包,多重背包等。 0-1背包 存在容量为 的背包 , 件体...

  • 0/1背包问题

    输出结果

  • 背包问题

    1、前言 背包问题是典型的动态规划问题,它有非常多的类型,本文讨论最常见的0-1背包问题 0-1背包问题描述:有一...

  • 0/1背包问题 0/1 Knapsack

    题目列表 相等子集划分问题 Equal Subset Sum Partition 416. 分割等和子集 子集和问...

  • 0-1背包问题(回溯法)

    0-1背包问题 在0 / 1背包问题中,需对容量为c 的背包进行装载。从n 个物品中选取装入背包的物品,每件物品i...

  • 0/1背包和多重背包问题

    Given weights and values of n items, put these items in a...

  • 背包问题之0-1背包

    背包问题是典型的动态规划例子。我们可将子问题的解存储下来,以免计算其母问题时需用到子问题结果而重复计算。 问题阐述...

  • 0-1背包问题

    摘抄:http://www.cnblogs.com/Anker/archive/2013/05/04/305907...

网友评论

      本文标题:0/1背包问题

      本文链接:https://www.haomeiwen.com/subject/ggwthftx.html