题目描述
求助一个算法:给定一个浮点数数组和一个目标值,在数组中找出最接近目标值的浮点数组合;
例如:数组[1.2, 1.5, 2.1, 3.5, 4.2],目标值:7.6,则结果为[1.2, 2.1, 4.2]
求助一个算法:给定一个浮点数数组和一个目标值,在数组中找出最接近目标值的浮点数组合;
例如:数组[1.2, 1.5, 2.1, 3.5, 4.2],目标值:7.6,则结果为[1.2, 2.1, 4.2]
暴力,子数组。
<?php
$nums = [1.2, 1.5, 2.1, 3.5, 4.2];
$target = 7.6;
$arr = [];
$cha = PHP_INT_MAX;
$result = [[]];
foreach ($nums as $num) {
foreach ($result as $item) {
$newItem = array_merge($item, [$num]);
if ($cha > $newCha = abs(array_sum($newItem) - $target)) {
$cha = $newCha;
$arr = $newItem;
}
$result[] = $newItem;
}
}
var_dump(
array_sum($arr)
, $arr
);
2 回答5.2k 阅读✓ 已解决
1 回答831 阅读✓ 已解决
1 回答839 阅读✓ 已解决
2 回答729 阅读
1 回答601 阅读
784 阅读
回溯+剪枝
时间复杂度:\( O(2^n) \)
空间复杂度:\( O(n) \)