Partition Equal Subset Sum
Given an integer array `nums`, return `true` if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or `false` otherwise.
Examples
Constraints
1 <= nums.length <= 2001 <= nums[i] <= 100
Dynamic Programming (0/1 Knapsack)
Approach
This problem is a variation of the 0/1 Knapsack problem. First, calculate the total sum of the array. If the sum is odd, it cannot be partitioned into two equal subsets, so return false. If the sum is even, we need to find if there exists a subset whose sum is exactly `target = sum / 2`. We use a set (or boolean array) to keep track of all possible sums we can generate using elements processed so far. For each number in `nums`, we iterate through our current set of reachable sums and add the new number to each of them to find new reachable sums. If we ever generate the `target`, we return true.
Complexity Analysis
Time complexity is bounded by the number of elements times the maximum possible sum we can reach (which is half the total sum). Space complexity is proportional to the target sum to store the reachable sums in the set.
class Solution { public boolean canPartition(int[] nums) { int sum = 0; for (int num : nums) { sum += num; } // If sum is odd, cannot be divided equally if (sum % 2 != 0) { return false; } int target = sum / 2; Set<Integer> dp = new HashSet<>(); dp.add(0); for (int num : nums) { Set<Integer> nextDp = new HashSet<>(); for (int t : dp) { if (t + num == target) { return true; } nextDp.add(t + num); nextDp.add(t); } dp = nextDp; } return dp.contains(target); }}