01背包(回溯版)

public class ZeroOneBag {
    static int value = 0, weight = 0, max = 0;

    public static void main(String[] args) {
        System.out.println(test());
    }

    private static int test() {
//        int[] weights = {1, 3, 4};
//        int[] weights = {2, 2, 3, 1, 5, 2};
//        int[] values = {15, 20, 30};
//        int[] values = {2, 3, 1, 5, 4, 3};
//        return zeroOne(weights, values, 1);
//        return zeroOne(weights, values, 4);

//        int[] weights = {1};
//        int[] values = {10};
//        return zeroOne(weights, values, 1);

//        int[] weights1 = {1, 2, 3};
//        int[] values1 = {2, 3, 4};
//        int bagWeight1 = 5;

//        int[] weights2 = {2, 3, 4};
//        int[] values2 = {3, 4, 5};
//        int bagWeight2 = 6;

//        int[] weights3 = {1, 3, 4, 5};
//        int[] values3 = {1, 4, 5, 7};
//        int bagWeight3 = 7;

        int[] weights = {4,3,8,10,2};
        int[] values = {6,2,10,4,1};
        return zeroOne(weights, values, 10);
    }

    private static int zeroOne(int[] weights, int[] values, int bagWeight) {
        backtracking(weights, values, bagWeight, 0);
        return max;
    }

    private static void backtracking(int[] weights, int[] values, int bagWeight, int start) {
        for (int i = start; i < weights.length; i++) {
            if (weight + weights[i] > bagWeight) {
                continue;
            }
            weight += weights[i];
            value += values[i];
            if (value > max) {
                max = value;
            }
            backtracking(weights, values, bagWeight, i + 1);
            weight -= weights[i];
            value -= values[i];
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值