您的位置:首页 > 其它

01背包问题实现探究

2017-01-09 18:10 323 查看
参考博文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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: