* Pack.php


class Pack {

/** @var int */
private $num;

/** @var int */
private $cap;

/** @var array{int} */
private $weightList;

/** @var array{int} */
private $valueList;

/**
* @var array{array}
*/
private $sumValueMatrix;

public function __construct($n, $m, $w, $v) {
$this->num = $n;
$this->cap = $m;
$this->weightList = $w;
array_unshift($this->weightList, 0);
$this->valueList = $v;
array_unshift($this->valueList, 0);
$this->sumValueMatrix = self::createMatrix($this->num + 1, $this->cap + 1, 0);
}

private static function createMatrix($x, $y, $initValue) {
/** @var $d2List array{array} */
$d2List = [];
for ($i = 0; $i < $x; $i++) {
/** @var $d1List array{int} */
$d1List = [];
for ($j = 0; $j < $y; $j++) {
array_push($d1List, $initValue);
}
array_push($d2List, $d1List);
}
return $d2List;
}

/**
* $sumV[$i][$j]表示将前i件物品列为备选,背包容量为$j时,能获得的最大价值;
* $w[$i]表示第i件物品的重量
* $v[$i]表示第$i件物品的价值
* @return mixed
*/
public function dp() {
$sumV = $this->sumValueMatrix;
$num = $this->num;
$capacity = $this->cap;
$w = $this->weightList;
$v = $this->valueList;

for ($i = 1; $i <= $num; $i++) {
for ($j = 1; $j <= $capacity; $j++) {
if ($j >= $w[$i]) {
// printf("i=%d, j=%d, j-w[i]=%d/n", $i, $j, $j-$w[$i]);
$sumV[$i][$j] = max($sumV[$i-1][$j - $w[$i]] + $v[$i], $sumV[$i-1][$j]);
} else {
$sumV[$i][$j] = $sumV[$i-1][$j];
}
}
}

/*
printf("[");
printf("[");
printf("%d", $sumV[0][0]);
for ($j = 1; $j < count($sumV[0]); $j++) {
printf(",%d", $sumV[0][$j]);
}
printf("]");
for ($i = 1; $i < count($sumV); $i++) {
printf(",/n[");
printf("%d", $sumV[$i][0]);
for ($j = 1; $j < count($sumV[0]); $j++) {
printf(",%d", $sumV[$i][$j]);
}
printf("]");
}
printf("]/n");
*/

return $sumV[$num][$capacity];
}
}

* test.php

/**
* Created by PhpStorm.
* User: mingzhanghui
* Date: 9/3/2019
* Time: 15:01
*/

function __autoload($className) {
include dirname(__FILE__)./.$className..php;
}

$num = 5;
$capacity = 10;
$weightList = [2,2,6,5,4];
$valueList = [6,3,5,4,6];

$q = new Pack($num, $capacity, $weightList, $valueList);
echo $q->dp().PHP_EOL;

>php test.php


[[0,0,0,0,0,0,0,0,0,0,0],

[0,0,6,6,6,6,6,6,6,6,6],

[0,0,6,6,9,9,9,9,9,9,9],

[0,0,6,6,9,9,9,9,11,11,14],

[0,0,6,6,9,9,9,10,11,13,14],

[0,0,6,6,9,9,12,12,15,15,15]]

15