Overview
Given an integer array nums, return true if you can partition it into two subsets with equal sum.
Constraints
1 <= nums.length <= 2001 <= nums[i] <= 100
Examples
canPartition([1, 5, 11, 5]); // => true ([1,5,5] and [11]) canPartition([1, 2, 3, 5]); // => false
Solution
Reveal solution
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 Set([0]);
for (const num of nums) {
const next = new Set(dp);
for (const s of dp) {
if (s + num === target) return true;
next.add(s + num);
}
dp.clear();
for (const v of next) dp.add(v);
}
return dp.has(target);
}Resources
partition-equal-subset-sum.js
Partition Equal Subset Sum
mediumcodingAlgorithmsDynamic Programming
Overview
Given an integer array nums, return true if you can partition it into two subsets with equal sum.
Constraints
1 <= nums.length <= 2001 <= nums[i] <= 100
Examples
canPartition([1, 5, 11, 5]); // => true ([1,5,5] and [11]) canPartition([1, 2, 3, 5]); // => false
Solution
Reveal solution
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 Set([0]);
for (const num of nums) {
const next = new Set(dp);
for (const s of dp) {
if (s + num === target) return true;
next.add(s + num);
}
dp.clear();
for (const v of next) dp.add(v);
}
return dp.has(target);
}Resources
NameTopicDifficulty
103 of 103 problems