递归求给定包裹装载量时货物的最大价值(从左到右)

从左往右的尝试模型2

1.问题描述

给定两个长度都为N的数组weights和values,weights[i]和values[i] 分别代表i号物品的重量和价值。 给定一个正数bag,表示一个载重bag的袋子,装载的物品不能超过这个重量。返回能装下最多的价值是多少?

(1)PHP实现

//index...之后的最大价值
//0...index-1上做了货物的选择,使得已经达到的重量是$aleadw
//如果返回-1,认为没有方案
//如果不返回-1,认为返回的值是真实价值
function maxValue($weights=[],$values=[],$index=0,$aleadW=0,$bag=0){
    if($aleadW >$bag)
        return -1;
    //重量没超
    if($index ==  count($weights))
        return 0;
    $p1 = maxValue($weights,$values,$index+1,$aleadW,$bag);
    $p2Next = maxValue($weights,$values,$index+1,$aleadW+$weights[$index],$bag);
    $p2 = -1;
    if($p2Next != -1){
        $p2 = $values[$index]+$p2Next;
    }

    return $p1>=$p2?$p1:$p2;
}
$weights=[10,12,14,31,21,30,18,20,50,91];
$values =[2, 4, 8, 10,13,15,21,9, 13,30];
$bag = 100;

$res = maxValue($weights,$values,0,0,$bag);

print($res);

另一种实现方法为:

//$rest为剩余空间
function
maxValue($weights=[],$values=[],$index=0,$rest){ if($rest < 0){ return -1; } // if($index == count($weights)){ return 0; } //有货也有空间 $p1 = maxValue($weights,$values,$index+1,$rest); $p2 = -1; $p2Next = maxValue($weights,$values,$index+1,$rest-$weights[$index]); if($p2Next!=-1){ $p2=$values[$index]+$p2Next; } return $p1>=$p2?$p1:$p2; } $weights=[10,12,14,31,21,30,18,20,50,91]; $values =[2, 4, 8, 10,13,15,21,9, 13,30]; $bag = 100; $res = maxValue($weights,$values,0,$bag); print($res);
原文地址:https://www.cnblogs.com/indifferent/p/14398989.html