编程语言
首页 > 编程语言> > PHP实现动态规划背包问题

PHP实现动态规划背包问题

作者:互联网

有一堆货物,有各种大小和价值不等的多个物品,而你只有固定大小的背包,拿走哪些能保证你的背包带走的价值最多

动态规划就是可以记录前一次递归过程中计算出的最大值,在之后的递归期间使用,以免重复计算。

<?php                                                                                                                                        
 
$thing_arr = array(
    array('size' => 9, 'weight' =>10),
    array('size' => 4, 'weight' => 5), 
    array('size' => 6, 'weight' => 4), 
    array('size' => 7, 'weight' => 9), 
);
 
$max_package_arr = array();
$max_thing_arr   = array();
 
function package($space)
{
    global $thing_arr, $max_package_arr, $max_thing_arr;
    if (isset($max_package_arr[$space])) return $max_package_arr[$space];
    $max_value = 0;
    foreach($thing_arr as $thing) 
    {   
        if (($rest_space = $space-$thing['size'])>0)
        {   
            if (($value = package($rest_space) + $thing['weight']) > $max_value )
            {   
                $max_package_arr[$space] = $max_value = $value;
                $max_thing_arr[$space] = $thing['weight'];
            }   
        }   
    }   
    return $max_value;
}
 
 
echo package(12);
print_r($max_thing_arr);

 

标签:arr,背包,weight,package,max,space,thing,PHP,动态
来源: https://www.cnblogs.com/gaosf/p/14331974.html