【发布时间】:2017-05-17 14:36:23
【问题描述】:
我正在努力解决这个问题:
给定一个由 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();
}
不幸的是,如果所有箱子都没有装满,但最后一件物品已经放不下,我不知道如何处理这种情况。 我想此时我想重新组织项目并重试不同的分布。但是怎么做呢?
我一直在努力解决这个问题,如果有任何帮助,我会很高兴的!
【问题讨论】:
标签: java bin-packing