背包问题

public class Main {

    public static void main(String[] args) {
        int [] a = {2,4,5,7,8,6,10} ;
        pack(14,a,0,new int[a.length]);
    }

    private static void pack(int total,int [] src,int offset,int [] bag){
        if (total == 0)
        {
            printBag(bag);
            return ;
        }
        // 选择一个比total小的元素
        while(offset < src.length && src[offset]>total)
            offset++ ;
        if (offset == src.length)
            return ;  //剩余的元素中没有小于total的了,查找失败
        //都这里offset元素具备放入包中的条件(比total小)
        //接下来有两种情况,将offset放入包中和不放入包中
        pack(total,src,offset+1,bag.clone());  //第一种情况,不放入包中
        //第二种情况,放入包中
        putBag(bag,src[offset]);//先把offset元素放入bag中
        pack(total - src[offset],src,offset+1,bag); //在剩余的元素中继续查找
    }

    private static void printBag(int []a) {
        for(int i:a)
            System.out.print(" " + i);
        System.out.println();
    }

    private static void putBag(int[] bag, int a) {
        int i = 0 ;
        while( i < bag.length && bag[i]!=0)
            i++ ;
        if (i < bag.length)
            bag[i] = a ;
    }
}

转载于:https://www.cnblogs.com/sunliho/archive/2010/07/06/1772529.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值