Partition Equal Subset Sum
Medium dynamic-programming
Description
Constraints
1 <= n <= 200; positive values
Examples
Input: nums = [1,5,11,5]
Output: true
Hints (1)
- Total must be even; then check whether a subset of half the total exists.
Solutions
Subset-sum to half. · Time O(n*target) · Space O(target)
func canPartition(nums []int) bool {
total := 0
for _, n := range nums {
total += n
}
if total%2 != 0 {
return false
}
target := total / 2
dp := make([]bool, target+1)
dp[0] = true
for _, n := range nums {
for s := target; s >= n; s-- {
if dp[s-n] {
dp[s] = true
}
}
}
return dp[target]
}
Subset-sum to half. · Time O(n*target) · Space O(target)
function canPartition(nums) {
const total = nums.reduce((a, b) => a + b, 0);
if (total % 2 !== 0) return false;
const target = total / 2;
const dp = new Array(target + 1).fill(false);
dp[0] = true;
for (const n of nums) {
for (let s = target; s >= n; s--) if (dp[s - n]) dp[s] = true;
}
return dp[target];
}
Subset-sum to half. · Time O(n*target) · Space O(target)
function canPartition($nums) {
$total = array_sum($nums);
if ($total % 2 !== 0) { return false; }
$target = intdiv($total, 2);
$dp = array_fill(0, $target + 1, false);
$dp[0] = true;
foreach ($nums as $n) {
for ($s = $target; $s >= $n; $s--) {
if ($dp[$s - $n]) { $dp[$s] = true; }
}
}
return $dp[$target];
}
Subset-sum to half. · Time O(n*target) · Space O(target)
def canPartition(nums):
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
dp = [False] * (target + 1)
dp[0] = True
for n in nums:
for s in range(target, n - 1, -1):
if dp[s - n]:
dp[s] = True
return dp[target]
Subset-sum to half. · Time O(n*target) · Space O(target)
function canPartition(nums: number[]): boolean {
const total = nums.reduce((a, b) => a + b, 0);
if (total % 2 !== 0) return false;
const target = total / 2;
const dp = new Array(target + 1).fill(false);
dp[0] = true;
for (const n of nums) {
for (let s = target; s >= n; s--) if (dp[s - n]) dp[s] = true;
}
return dp[target];
}
Create a free account to submit solutions, track progress and save problems.
Create account