Example 1
- Input
- nums = [1, 5, 11, 5]
- Output
- true
The total is 22. Select positions 0, 1 and 3 for [1, 5, 5], leaving [11]; both sums are 11. Selecting the single 11 also proves the same answer.
Split the array into two groups with the same total, which is possible exactly when some subset adds up to half of the overall sum. Return true when such a subset exists and false otherwise.
Given an integer array nums, return true if the array can be split into two subsets whose sums are equal, and false otherwise. Every element must belong to exactly one of the two subsets.
Both subsets share the same sum, so each one must total exactly half of the whole array sum. When the total sum is odd, no equal integer split exists.
The task therefore reduces to deciding whether some subset of nums adds up to total / 2.
The total is 22. Select positions 0, 1 and 3 for [1, 5, 5], leaving [11]; both sums are 11. Selecting the single 11 also proves the same answer.
The total is 11. Two equal integer sums would have to be 5.5 each, so parity alone rules out a partition.
The total is even and the target is 1, but the only subset sums are 0 and 2. Even total is necessary, not sufficient.
The total is 8 and the target is 4. Values 1 and 2 can make only 0, 1, 2 or 3, while 5 is too large. Reusing the same 1 or 2 would incorrectly create 4.
If the total is 22, both groups must sum to 11. Finding just one subset of sum 11 is enough: every unused position forms the other group, whose sum is 22 - 11. In Example 1, [11] and [1, 5, 5] are both witnesses. Each array position can be selected once, even when its value repeats. Rather than remembering every subset, remember which totals those subsets can reach; different subsets with the same total have identical possibilities when the next number arrives.
Reveal Recursive Subset Search: intuition, complexity, and code
When the question is whether some subset hits an exact total, convert it to a target-sum check and track reachable sums with a 1D table scanned backwards.