参考博文http://blog.csdn.net/mu399/article/details/7722810
另外bilibili有个讲背包01的视频也挺生动的。
<?php //背包01问题 class Item{ public $weight; public $value; public function __construct($weight,$value){ $this->weight = $weight; $this->value = $value; } } class Bag{ private $items; public function __construct($items){ $this->items = $items; } private $resultMap = array(); function bestBag($k,$w){ if($k==0 || $w==0){ return 0; } if(isset($this->resultMap[$k][$w])){ return $this->resultMap[$k][$w]; } if($k==1) { if ($this->items[$k]->weight > $w) { return 0; } else { return $this->items[$k]->value; } } $res1 = $this->bestBag($k-1,$w); if($w-$this->items[$k]->weight>0){ $res2 = $this->bestBag($k-1,$w-$this->items[$k]->weight)+$this->items[$k]->value; }else{ $res2 = 0; } $result = max($res1,$res2); if(!isset($this->resultMap[$k][$w])){ $this->resultMap[$k][$w] = $result; } return $result; } } $items = array(); for($i = 1;$i<6;$i++){ $item = new Item($i,$i+3); $items[$i] = $item; } print_r($items); $bagTest = new Bag($items); echo $bagTest->bestBag(5,60);exit;