<?php class Item{ private $weight = 0; private $price = 0; private $name = ""; /** * Item constructor. * @param string $name * @param int $price * @param int $weight */ public function __construct(string $name ,int $weight, int $price) { $this->name = $name; $this->weight = $weight; $this->price = $price; } /** * @return string */ public function getName(): string { return $this->name; } /** * @param string $name */ public function setName(string $name) { $this->name = $name; } /** * @return int */ public function getWeight(): int { return $this->weight; } /** * @param int $weight */ public function setWeight(int $weight) { $this->weight = $weight; } /** * @return int */ public function getPrice(): int { return $this->price; } /** * @param int $price */ public function setPrice(int $price) { $this->price = $price; } } class Bags{ const DEFAULT_VALUE = 0; private $capacity = 0; private $items = []; private $tables = []; public function __construct( $capacity ) { $this->capacity = $capacity; } public function addItem( Item $item ){ return array_push($this->items, $item); } //获取背包最大价值 public function getMaxValue(){ //建立二维表 $this->initTable(); $capacitys = $this->getCapacity(); $itemCount = count($this->items); $curItem = null; $curVal = 0; $curWeight = 0; for ( $i = 1; $i <= $itemCount; $i++ ){ for( $curCapacity=1; $curCapacity <= $capacitys; $curCapacity++ ){ $curItem = $this->items[$i-1]; $curVal = $curItem->getPrice(); $curWeight = $curItem->getWeight(); $this->tables[$i][$curCapacity] = $this->tables[$i-1][$curCapacity] ?? static::DEFAULT_VALUE; $spareVal = $this->tables[$i-1][$curCapacity-$curWeight]['val'] ?? static::DEFAULT_VALUE; $lastVal = $this->tables[$i-1][$curCapacity]['val'] ?? static::DEFAULT_VALUE; $maxVal = $curVal + $spareVal; if( $curCapacity >= $curWeight && ($maxVal > $lastVal) ){ $content = "name:".$curItem->getName()." ,price: ".$curItem->getPrice() ." weight:".$curItem->getWeight(); $this->tables[$i][$curCapacity] = [ 'val'=>$maxVal , 'content'=> array_merge( $this->tables[$i-1][$capacitys-$curWeight]['content']??[], [$content]) ]; } } } return $this->tables[$itemCount][$capacitys]; } public function initTable(){ $capacitys = $this->getCapacity(); $itemCount = count($this->items); for ( $i = 1; $i <= $itemCount; $i++ ){ for( $j=1; $j<= $capacitys; $j++ ){ $this->tables[$i][$j] = [ 'val'=> static::DEFAULT_VALUE, 'content'=>'' ]; } } return $this->tables; } //根据背包计算 public function getCapacity(){ return $this->capacity; } public function getTables(){ return $this->tables; } } $bag = new Bags( 4 ); $item1 = new Item('吉他', 1, 1500); $item2 = new Item('音响', 4, 3000); $item3 = new Item('笔记本电脑', 3, 2000); $item4 = new Item('钻石',1 , 6000); $item5 = new Item('钻石2',1 , 20000); $bag->addItem($item5); $bag->addItem($item4); $bag->addItem($item1); $bag->addItem($item2); $bag->addItem($item3); $maxVal = $bag->getMaxValue(); print_r($maxVal);