背包问题

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 ;
    }
}

posted on 2010-07-06 23:32  sunliho  阅读(114)  评论(0编辑  收藏  举报