Partition Equal Subset Sum
Given an array nums
Example 1
Output: true
Explanation: [1, 5, 5] and [11].
Example 2
Output: false
Explanation: the total is 11, which is odd.
How to Think About It
Step 1: Reduce to "is there a subset with sum target?"
If the total is odd, the answer is false. Otherwise one subset must sum to target = total / 2
Step 2: Brute force: include or exclude each number
Each number is either in the subset or not. A recursive search tries both, which is O(2n):
Step 3: Track which sums are reachable
Only the sums matter, and they are at most targetreachable[s]ss - v
Step 4: Loop the sums downward
Updating from high sums to low means reachable[s - v]
Walkthrough
nums = [1, 5, 11, 5]
| Number added | Reachable sums up to 11 |
|---|---|
| start | 0 |
| 1 | 0, 1 |
| 5 | 0, 1, 5, 6 |
| 11 | 0, 1, 5, 6, 11 |
| 5 | 0, 1, 5, 6, 10, 11 |
11 is reachable, so the answer is true.
Java Solution
A boolean array of size target + 1
public class PartitionEqualSubset {
public boolean canPartition(int[] nums) {
int total = 0;
for (int v : nums) {
total += v;
}
if (total % 2 != 0) {
return false; // an odd total cannot split into two equal halves
}
int target = total / 2;
boolean[] reachable = new boolean[target + 1]; // reachable[s]: some subset sums to s
reachable[0] = true;
for (int v : nums) {
for (int s = target; s >= v; s--) { // go down so each number is used once
reachable[s] = reachable[s] || reachable[s - v];
}
}
return reachable[target];
}
}
The original implementation,
Complexity
- Time: O(n × target).
- Space: O(target).
Counting the subsets instead of checking for one gives