Given a list of positive integers nums, return True if its numbers can be split into two groups with equal sums, or False otherwise.
Every number goes into exactly one of the two groups. Numbers that repeat in nums are separate numbers: each copy goes into one group.
Example 1:
Input: nums = [1, 5, 11, 5] Output: True Explanation: [1, 5, 5] and [11] both add up to 11.
Example 2:
Input: nums = [1, 2, 3, 5] Output: False Explanation: The total is 11. It is odd, so it can't be split into two equal halves.
Example 3:
Input: nums = [1, 2, 5] Output: False Explanation: The total is 8, so each group would have to add up to 4. But the numbers can only make 1, 2, 3 (1 + 2), 5, 6 (1 + 5), 7 (2 + 5) and 8: never 4. Using the 1 four times or the 2 twice would make 4, but each number can be used only once.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 100
Note:
Your algorithm should run in O(n · sum) time and use O(sum) extra space, where n is the number of values in nums and sum is their total.
If the total is odd, the answer is
False. Otherwise the question becomes: can some of the numbers add up to exactly half, the total divided by 2? The other numbers then make the other half. Trying every group is far too slow: 200 numbers can be grouped in 2200 ways. Keep a table of booleans instead: can[s] says whether some of the numbers seen so far add up to s, for every s from 0 to half. Before any number is seen, only can[0] is True: no numbers at all make 0.
Add the numbers one at a time. For a number
num, every sum that could be made before gives a new sum with num added: can[s] becomes True when can[s - num] is. Go over the sums from half down to num. Going down, can[s - num] is still the value from before this number, so each number is used at most once.Why down, when Coin Change II goes up: in Coin Change II the loop over the sums goes up on purpose. There
ways[a - coin] may already count the same coin, and that is how one coin value is used again and again. Here going up would reuse a number: on [1, 2, 5] it would make 4 as 1 + 1 + 1 + 1 or 2 + 2, and wrongly answer True for Example 3.
Each of the
n numbers goes over at most half + 1 sums, with a constant amount of work for each: O(n · sum) time. The table holds half + 1 booleans: O(sum) space.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
