A PHP algorithm is required to select the sum of the numbers in a string of arrays and the algorithm to nearest (<=) the given value.
Example: Upper value: 38 Given array value 15,20,10, 6
Correct results selected: 20 10 6
How can this be achieved? To find a concrete way to achieve
Before the order from large to small, and then add, found to choose 20 15 10, but in fact the best is 20 10 6, to help ...
Reply content:
A PHP algorithm is required to select the sum of the numbers in a string of arrays and the algorithm to nearest (<=) the given value.
Example: Upper value: 38 Given array value 15,20,10, 6
Correct results selected: 20 10 6
How can this be achieved? To find a concrete way to achieve
Before the order from large to small, and then add, found to choose 20 15 10, but in fact the best is 20 10 6, to help ...
$a = 38;
$arr = Array (15,20,10,6);
function SS ($a, $arr) {
$count = count($arr);$array = array();for($i=0;$i<$count;$i++){ $r = $arr[$i]; unset($arr[$i]); $sum = abs(array_sum($arr) - $a); $array[$sum][] = $arr; $arr[] = $r;}return $array;
}
$DD = SS ($a, $arr);
Ksort ($DD);
Print_r ($DD);
Print, absolute minimum, nearest
Array
(
[2] => Array ( [0] => Array ( [1] => 20 [2] => 10 [3] => 6 ) )[3] => Array ( [0] => Array ( [3] => 6 [4] => 15 [5] => 20 ) )[7] => Array ( [0] => Array ( [2] => 10 [3] => 6 [4] => 15 ) [1] => Array ( [4] => 15 [5] => 20 [6] => 10 ) )
)
The first thought must be the violence for loop algorithm, this time complexity is a bit high, in n^2, a small amount of data can be achieved.
The result is 20 15 10 and obviously less than 38 ah, if the judgment can be filtered out, it is impossible to give you the best one-time, unless just .
The algorithm can be divided into dynamic programming inside, the core is for the loop, very similar.
This is the classic backpack problem, recommended to read the backpack question nine talk
The method of solving 01 knapsack problem by Dynamic programming
$maxSize = 38;$arr = array(15, 20, 10, 6);$result = array();$answers = array();$currSize = 36;$len = count($arr);for ($i = 0; $i < $len; $i++) { $result[] = array(); for ($j = 0; $j <= $maxSize; $j++) { $result[$i][$j] = 0; }}for ($i = 0; $i <= $maxSize; $i++) { for ($j = 0; $j < $len; $j++) { if ($arr[$j] > $i) { if ($j === 0) $result[$j][$i] = 0; else $result[$j][$i] = $result[$j - 1][$i]; } else { if ($j === 0) $result[$j][$i] = $arr[$j]; else $result[$j][$i] = max($result[$j - 1][$i], $result[$j - 1][$i - $arr[$j]] + $arr[$j]); } }}// 找出答案for ($i = $len - 1; $i >= 0 && $currSize !== 0; $i--) { if ($result[$i][$currSize] - $result[$i - 1][$currSize - $arr[$i]] === $arr[$i]) { $answers[] = $arr[$i]; $currSize -= $arr[$i]; }}
Ask for help ~update