背包装入最大价值总和

$list = [
    [
        'id' => 'a',
        'weight' => 2,
        'money' => 6
    ],
    [
        'id' => 'b',
        'weight' => 2,
        'money' => 3
    ],
    [
        'id' => 'c',
        'weight' => 6,
        'money' => 5
    ],
    [
        'id' => 'd',
        'weight' => 5,
        'money' => 4
    ],
    [
        'id' => 'e',
        'weight' => 4,
        'money' => 6
    ]
];
 
$pack = 10;
 
$result = [];
 
$max = ['money' => 0];
 
foreach ($list as $item) {
    $process = [
        'count' => $item['weight'],
        'money' => $item['money'],
        'list' => [$item]
    ];
    foreach ($list as $_item) {
        if ($_item !== $item) {
            if ($process['count'] + $_item['weight'] <= $pack) {
                $process['count'] += $_item['weight'];
                $process['money'] += $_item['money'];
                $process['list'][] = $_item;
            }
        }
        if ($process['count'] === $pack) break;
    }
    $result[] = $process;
    if ($max['money'] < $process['money']) $max = $process;
}
 
//全部组合
print_r($result);
 
//价值最大组合
print_r($max);

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

微信扫一扫

微信扫一扫

微信扫一扫,分享到朋友圈

背包装入最大价值总和