使用递归bin算法挣扎:固定数量的bin?

时间:2017-05-17 14:36:23

标签: java bin-packing

我想弄清楚这一点:

  

给定N个正整数的集合S,任务是将它们划分为K个子集,使得每个K个子集中的元素值之和相等。

我的方法是使用第一个拟合递减算法。我按大小对整数进行排序并填充它们:

public int getResult() {
    Collections.sort(in, Collections.reverseOrder()); // sort input by size (big to small)
    bins.add(new Bin(binSize)); // add first bin
    for (Integer currentItem : in) {
        // iterate over binlist and try to put the item into the first one it fits into
        boolean putItem = false; // did we put the item in a bin?
        int currentBin = 0;
        while (!putItem) {
            if (currentBin == bins.size()) {
                // item did not fit in last bin.
                // No clue what to do here
                putItem = true;
            } else if (bins.get(currentBin).put(currentItem)) {
                // item fit in bin
                putItem = true;
            } else {
                // try next bin
                currentBin++;
            }
        }
    }
    return bins.size();
}

不幸的是,如果所有垃圾箱都没有装满,我不知道如何处理这种情况,但最后一项不再合适。 我想在这一点上我想重组项目并重试不同的发行版。但是如何?

我一直试图解决这个问题一段时间,我会很高兴有任何帮助!

1 个答案:

答案 0 :(得分:0)

如果你面前有实际的垃圾箱,你会怎么做?如果某个号码不适合垃圾箱,您需要返回上一步,换上之前放入的号码。如果这不起作用,您需要返回,交换等等。

你帖子的标题说你正在寻找一个递归的解决方案。您的解决方案不是递归的。递归函数调用自身,可能使用减少的参数集,并且递归函数具有“基本情况”,或者知道它已尽可能远的方式,并且它可以声明成功。

以下是一个例子:

public int fibonacci(int n)  {
    // Here are the base cases (Fibonacci happens to have two)
    if (n==0) {
      return 0;
    }
    else if (n==1) {
      return 1;
    }

    // Otherwise, call this function again, changing the parameters
    return fibonacci(n - 1) + fibonacci(n - 2);
}

你会如何编写递归的bin-filling函数?您可以从S放置一个数字X,然后使用没有X的S再次调用您的函数。您还应该传递垃圾箱。想想你的基本案例是什么;我认为当S为空且箱已满时,你会宣布成功。如果S不是空的,请尝试拟合下一个X.如果它不适合,你需要回溯,可能是通过做“返回假”这样的事情......你的函数需要知道在通话时该怎么做本身返回false。

祝你好运!