Warum müssen bei einer dynamischen Programmierung die Gewichte ganzzahlige Werte sein?

In dynamic programming, the weights must be integer values because the algorithm relies on optimal substructure and overlapping subproblems. If the weights were not integers, the algorithm could potentially have infinite combinations of weights to consider, making it computationally infeasible to find the optimal solution.

// Example PHP code snippet with integer weights for dynamic programming
$weights = [1, 2, 3, 4, 5]; // Integer weights
$values = [10, 20, 30, 40, 50];
$capacity = 8;

function knapsack($weights, $values, $capacity) {
    $n = count($weights);
    $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];
}

echo knapsack($weights, $values, $capacity); // Output: 90