416. Partition Equal Subset Sum #1529
-
Topics: Given an integer array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if a given integer array can be partitioned into two subsets such that the sum of the elements in both subsets is equal. This can be efficiently achieved using a dynamic programming approach. Approach
Let's implement this solution in PHP: 416. Partition Equal Subset Sum <?php
/**
* @param Integer[] $nums
* @return Boolean
*/
function canPartition($nums) {
$sum = array_sum($nums);
if ($sum % 2 != 0) {
return false;
}
$target = $sum / 2;
$dp = array_fill(0, $target + 1, false);
$dp[0] = true;
foreach ($nums as $num) {
for ($j = $target; $j >= $num; $j--) {
$dp[$j] = $dp[$j] || $dp[$j - $num];
}
}
return $dp[$target];
}
// Example Test Cases
var_dump(canPartition([1, 5, 11, 5])); // true
var_dump(canPartition([1, 2, 3, 5])); // false
?> Explanation:
This approach efficiently checks for the possibility of partitioning the array using dynamic programming, ensuring optimal time and space complexity. |
Beta Was this translation helpful? Give feedback.
We need to determine if a given integer array can be partitioned into two subsets such that the sum of the elements in both subsets is equal. This can be efficiently achieved using a dynamic programming approach.
Approach