Gibt es eine effizientere Lösung für das Knapsack-Problem in PHP, die die Laufzeit optimiert und die Ergebnisse verbessert?
Das Knapsack-Problem beinhaltet das Finden der optimalen Kombination von Gegenständen mit begrenztem Gewicht in einem Rucksack, um den Gesamtwert zu maximieren. Eine effizientere Lösung für dieses Problem kann durch die Verwendung von dynamischer Programmierung erreicht werden, um die Laufzeit zu optimieren und die Ergebnisse zu verbessern.
function knapsack($capacity, $weights, $values, $n) {
$dp = array_fill(0, $n + 1, array_fill(0, $capacity + 1, 0));
for ($i = 1; $i <= $n; $i++) {
for ($w = 1; $w <= $capacity; $w++) {
if ($weights[$i - 1] <= $w) {
$dp[$i][$w] = max($values[$i - 1] + $dp[$i - 1][$w - $weights[$i - 1]], $dp[$i - 1][$w]);
} else {
$dp[$i][$w] = $dp[$i - 1][$w];
}
}
}
return $dp[$n][$capacity];
}
$weights = [2, 3, 4, 5];
$values = [3, 4, 5, 6];
$capacity = 8;
$n = count($weights);
echo knapsack($capacity, $weights, $values, $n);
Related Questions
- Are there any specific PHP functions or libraries that can simplify the process of moving data between databases?
- What are the security concerns associated with automatically opening links in new windows using PHP?
- In PHP, what are the advantages and disadvantages of fetching all data rows at once versus fetching them in a loop when using mysql_fetch_assoc?