Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Example 1:
Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
- 1 <= nums.length <= 200
- 1 <= nums[i] <= 100
Runtime: 988 ms, faster than 9.15% of JavaScript online submissions for Partition Equal Subset Sum.
Memory Usage: 68.8 MB, less than 44.54% of JavaScript online submissions for Partition Equal Subset Sum.
/**
* @param {number[]} nums
* @return {boolean}
*/
var canPartition = function(nums) {
const sum = nums.reduce((prev, current) => prev + current, 0);
if (sum % 2 !== 0) {
return false;
}
const halfSum = sum / 2;
const size = nums.length;
const dp = Array.from({ length: size + 1 })
.map(
_ => Array.from({ length: halfSum + 1 }).map(_ => false)
);
for (let i = 0; i <= size; i++) {
dp[i][0] = true;
}
for (let i = 1; i <= size; i++) {
for (let j = 1; j <= halfSum; j++) {
if (j - nums[i] < 0) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j - nums[i]] || dp[i - 1][j];
}
}
}
return dp[size][halfSum];
};
Runtime: 132 ms, faster than 80.28% of JavaScript online submissions for Partition Equal Subset Sum.
Memory Usage: 40.9 MB, less than 81.51% of JavaScript online submissions for Partition Equal Subset Sum.
/**
* @param {number[]} nums
* @return {boolean}
*/
var canPartition = function(nums) {
const sum = nums.reduce((prev, current) => prev + current, 0);
if (sum % 2 !== 0) {
return false;
}
const halfSum = sum / 2;
const size = nums.length;
const dp = Array.from({ length: halfSum + 1 }).map(_ => false);
dp[0] = true;
for (let i = 1; i <= size; i++) {
for (let j = halfSum; j > 0; j--) {
if (j - nums[i] >= 0) {
dp[j] = dp[j] || dp[j - nums[i]];
}
}
}
return dp[halfSum];
};