2020-12-22

01背包问题回溯法Java实现

其实回溯法实现01背包问题很简单,没有网上说的那么复杂,简单概括来说就是每次进行搜索如果搜索到叶子节点且符合条件就存储这个值,如果不符合条件就回溯,返回到上一层的背包的容量和所装入的物品价值,这样遇到不符合条件就回溯直到搜索完整个树,最优结果就出来了
代码如下

public class BackTrackingKnapsack01Test {
    public int []weight;
    public int []value;
    public int MaxWeight;
    int count;
    int []take; //用来标记路径
    int []BestChoice;
    int curValue=0;
    int curWeight=0;
    int bestValue=0;

    public void init(int []weight,int []value,int MaxWeight){
        this.weight = weight;
        this.value = value;
        this.MaxWeight = MaxWeight;
        count = value.length;
        BestChoice = new int[count];
        take = new int[count];
        if (weight==null||weight.length==0||
                value==null||value.length==0||
                weight.length!=value.length||MaxWeight<0){
            System.out.println("参数出现错误");
            return;
        }
    }

    public int[] find(int level){
        if (level > count-1){
            if (curValue>bestValue){
                bestValue = curValue;
                for (int i=0; i<take.length; i++){
                    BestChoice[i] = take[i];
                }
            }
        }else {
            for (int i=0; i<2; i++){
                take[level] = i;
                if (i==0){
                    find(level+1);
                }else{
                    if (curWeight+weight[level]<=MaxWeight){
                        curWeight+=weight[level];
                        curValue+=value[level];
                        find(level+1);
                        //回溯
                        curWeight-=weight[level];
                        curValue-=value[level];
                    }
                }
            }
        }
        return BestChoice;
    }

    public static void main(String[] args) {
        BackTrackingKnapsack01Test B01Test = new BackTrackingKnapsack01Test();
        B01Test.init(new int[]{16, 15, 15},new int[]{44,25,20},30);
        int[] result = B01Test.find(0);
        System.out.print("最佳选择为:[");
        for (int i=0; i<result.length;i++){
            if (i==result.length-1){
                System.out.print(result[i]+"]");
            }else {
                System.out.print(result[i]+",");
            }
        }
        System.out.print("\n此时价值最大,即"+B01Test.bestValue);

    }


}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值