Leetcode 416. Partition Equal Subset Sum
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 the elements in both subsets is equal.
Before jumping into the solution, let’s consider some clarifying questions that could help understand edge cases and constraints better:
1 <= nums.length <= 200
1 <= nums[i] <= 100
To determine if the array can be partitioned into two subsets with equal sum:
total_sum / 2
.dp
) where dp[i]
will be true
if a subset sum of i
can be achieved with the elements processed so far.dp[0]
to true
because a sum of 0
is always possible (with an empty subset).dp
array from the end to the start to prevent using the same element multiple times.#include <vector>
#include <numeric>
#include <iostream>
class Solution {
public:
bool canPartition(std::vector<int>& nums) {
int totalSum = std::accumulate(nums.begin(), nums.end(), 0);
// If the total sum is odd, it can't be divided into two equal subsets
if (totalSum % 2 != 0) return false;
int target = totalSum / 2;
std::vector<bool> dp(target + 1, false);
// A subset sum of 0 is always possible with an empty subset
dp[0] = true;
for (const int& num : nums) {
// Update dp array from end to start to avoid reusing the same element
for (int i = target; i >= num; --i) {
dp[i] = dp[i] || dp[i - num];
}
}
return dp[target];
}
};
int main() {
Solution sol;
std::vector<int> nums = {1, 5, 11, 5};
bool canPartition = sol.canPartition(nums);
std::cout << (canPartition ? "True" : "False") << std::endl; // Output: True
return 0;
}
n
is the number of elements in the array.target
is half of the total sum of the array.target + 1
to store our DP states.This solution efficiently checks the possibility of partitioning the array into two subsets with equal sums using dynamic programming.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?