给定一个数组,计算该数组中能否分成两部分,使这两部分的和相等

思路:0-1背包问题,重量和价值相等,容量为数组和的二分之一。

背包问题:https://blog.csdn.net/why444216978/article/details/104462639

<?php

function dp($w, $v, $index, $cap, &$history = [])
{
    if ($index < 0 || $cap <= 0){
        return 0;
    }

    $key = sprintf("%d-%d", $index, $cap);
    if (!empty($history[$key])){
        return $history[$key];
    }

    $res = dp($w, $v, $index - 1, $cap, $history);
    if ($w[$index] <= $cap){
        return max( $res, $v[$index] + dp($w, $v, $index - 1, $cap - $w[$index], $history) );
    }

    $history[$key] = $res;

    return $res;
}

function func($arr)
{
    $sum = array_sum($arr);
    $half = $sum / 2;

    if ($half * 2 !== $sum){
        return false;
    }

    $res = dp($arr, $arr, count($arr) - 1, $half);

    return $res === $half;
}

$arr = [1, 1, 3, 2, 4, 5, 2];
var_dump(func($arr));
发布了226 篇原创文章 · 获赞 31 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/104462886