【发布时间】:2019-06-28 14:39:05
【问题描述】:
给定大量正整数“权重”,例如[ 2145, 8371, 125, 10565, ... ],以及一个正整数“重量限制”,例如15000,我想将权重划分为一个或多个较小的数组,条件如下:
- 我想尽量减少分区数。
- 单个分区的总和不能超过重量限制。 (请注意,没有单个重量会超过此限制。)
我怀疑这个问题的复杂度很高。作为答案,我感兴趣的是:
- 最佳解决方案
- 不是很理想,但可以快速运行(近似)的解决方案
当前非最优方法:(基本贪心算法;JavaScript)
function minimizePartitions(weights, weightLimit) {
let currentPartition = [];
let currentSum = 0;
let partitions = [ currentPartition ];
for (let weight of weights) {
if (currentSum + weight > weightLimit) {
currentPartition = [];
currentSum = 0;
partitions.push(currentPartition);
}
currentPartition.push(weight);
currentSum += weight;
}
return partitions;
}
let weights = [3242, 987, 1222, 7299, 400, 10542, 10678, 513, 3977];
console.log(minimizePartitions(weights, 15000));
【问题讨论】:
-
您希望将结果作为数组数组?请添加预期的输出。
-
你能展示一下你尝试过的东西吗?一些开始,一些注意事项..
-
你不能用贪心算法解决这个问题,这是一个NP-complete problem@GershomMaes
-
@Margon 我有一种感觉!有这个特定问题的名称吗?
-
@MaheerAli 在这种情况下需要有 3 个分区:
[ [ 2, 2 ], [ 14999 ], [ 14999 ] ]
标签: javascript algorithm