动态规划之 -- 01背包问题

有N件物品和一个容量为V的背包,第i件物品消耗的容量为Ci,价值为Wi,求解放入哪些物品可以使得背包中总价值最大。

解法一:

static int[] w = new int[]{0, 2, 3, 5, 5};
static int[] v = new int[]{0, 2, 4, 3, 7};

public static int test2(int i , int c){
    int result = 0;

    if(i == 0 || c == 0){

        return 0;

    }else if(w[i] > c){

        result = test2(i-1,c);

    }else {
        int temp1 = test2(i - 1, c);
        int temp2 = test2(i-1,c-w[i])+v[i];

        result = Math.max(temp1,temp2);

    }

    return result;
}

 

解法二:

static int[] w = new int[]{0, 2, 3, 5, 5};

static int[] v = new int[]{0, 2, 4, 3, 7};

static int[][] result = new int[5][11];
 public static int test3(int i , int c){
       // 初始化
        for(int n =0; n <= i; n++){
            result[n][0]=0;
        }

        for(int n = 0 ; n <= c; n++){
            result[0][n]=0;
        }

        for(int n = 1; n <= i; n ++){
            for (int m = 1; m <= c; m++) {
                if(m < w[n]){
                    result[n][m] = result[n-1][m];
                }else {
                    if(result[n-1][m]>result[n-1][m-w[n]]+v[n]){
                        result[n][m] = result[n-1][m];
                    }else {
                        result[n][m] = result[n-1][m-w[n]]+v[n];
                    }
                }

            }

        }

        return result[i][c];

 }

 参考文档:

https://www.cnblogs.com/mfrank/p/10849505.html

https://zhuanlan.zhihu.com/p/93857890

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值