编程语言
首页 > 编程语言> > java – 打印输出0/1 KnapSack(递归蛮力)

java – 打印输出0/1 KnapSack(递归蛮力)

作者:互联网

public static int KnapSack(int capacity, Item[] items, int numItems) {
    if (numItems == 0 || capacity == 0)
        return 0;
    if (items[numItems-1].weight > capacity)
        return KnapSack(capacity, items, numItems-1);
    else {
        int took = items[numItems-1].value + KnapSack(capacity - items[numItems-1].weight, items, numItems-1);
        int left = KnapSack(capacity, items, numItems-1);
        return Math.max(took, left);
    }     
}  

所以我有一个工作的0/1递归强力算法为KnapSack问题工作.我想知道打印出工作解决方案的方法是什么(即从项目集中收集到背包里的物品).我已经尝试了很多东西,例如添加到列表中并尝试跟踪我添加的内容,但是没有一个可以解决实现或设计问题.所以我来这里寻求帮助,谢谢!

解决方法:

要跟踪拍摄的项目,请尝试以下操作:

public static int KnapSack(int capacity, Item[] items, int numItems, ArrayList<Integer> taken) {
    if (numItems == 0 || capacity == 0)
        return 0;
    if (items[numItems-1].weight > capacity)
        return KnapSack(capacity, items, numItems-1, taken);
    else {
        final int preTookSize = taken.size();
        final int took = items[numItems-1].value + KnapSack(capacity - items[numItems-1].weight, items, numItems-1, taken);

        final int preLeftSize = taken.size();
        final int left = KnapSack(capacity, items, numItems-1, taken);

        if (took > left) {
            if (taken.size() > preLeftSize)
                taken.removeRange(preLeftSize, taken.size());
            taken.add(Integer.valueOf(numItems - 1));
            return took;
        }
        else {
            if (preLeftSize > preTookSize)
                taken.removeRange(preTookSize, preLeftSize);
            return left;
        }
    }     
}

这可能不是最有效的,但我认为它应该有效.

(为了提高效率,您可以尝试将所采用的ArrayList预先分配为“足够大”,以便在递归循环期间不需要进行分配.)

标签:java,recursion,knapsack-problem
来源: https://codeday.me/bug/20190517/1120906.html