<?php
function getNeedConisNum(array $conis, $amount)
{
if (empty($conis) || empty($amount)) {
return -1;
}
rsort($conis);
$find = $conis;
$finish = [];
while (!empty($find)) {
if (empty($find)) {
break;
}
$res = array_shift($find);
if (!is_array($res)) {
$res = array($res);
}
if (array_sum($res) == $amount) {
$finish[] = count($res);
}
if (array_sum($res) > $amount) {
continue;
} else {
foreach ($conis as $newConi) {
$res[] = $newConi;
$find[] = $res;
}
}
}
if (empty($finish)) {
return -1;
}
return min($finish);
}
$conis = [1, 2, 5];
$amount = 11;
echo getNeedConisNum($conis, $amount);
echo "\n";
$conis = [2];
$amount = 3;
echo getNeedConisNum($conis, $amount);
复制代码
结果
3
-1复制代码