This article analyzes the dynamic programming of PHP to solve 0-1 knapsack problem. Share to everyone for your reference. The specific analysis is as follows:
Knapsack problem Description: A backpack that bears the maximum weight of W, now has n items, each item weighs t, and the value of each item is v.
To make this backpack the most weight (but not more than W), but also need the most valuable backpack.
Train of thought: Define a two-dimensional array, one dimension for the item quantity (expression for each item), two-dimensional is the weight (not exceeding the maximum, here is 15), the following array a,
The principle of dynamic programming, Max (OPT (i-1,w), wi+opt (I-1,W-WI)), the maximum value,
Opt (I-1,W-WI) means the last optimal solution
<?php
//This is I write according to the dynamic programming principle
//MAX (opt (i-1,w), wi+opt (I-1,W-WI))
//backpack can be loaded with the maximum weight
$w =15;
Here are four items, the weight of each item
$DX =array (3,4,5,6);
The value of each item
$QZ =array (8,7,4,9);
Defines an array
$a =array ();
Initialize for
($i =0 $i <=15; $i + +) {$a [0][$i]=0;}
For ($j =0 $j <=4; $j + +) {$a [$j][0]=0;}
Opt (i-1,w), wi+opt (I-1,W-WI) for
($j =1; $j <=4; $j + +) {for
($i =1; $i <=15; $i + +) {
$a [$j] [$i]= $a [ $j -1][$i];
is not greater than the maximum w=15
if ($dx [$j -1]<= $w) {
if!isset ($a [$j -1][$i-$DX [$j-1]]) continue;
Wi+opt (i-1,wi)
$tmp = $a [$j -1][$i-$dx [$j -1]]+ $QZ [$j-1];
Opt (i-1,w), wi+opt (I-1,W-WI) => to compare
if ($tmp > $a [$j] [$i]) {
$a [$j] [$i]= $tmp;
}
}}}
//Print this array, the value of the output is the maximum value for
($j =0 $j <=4; $j + +) {for
($i =0; $i <=15; $i + +) {
echo $a [$j] [$i ]." /t ";
} echo "/n"
;
>
I hope this article will help you with your PHP program design.