You get an array of non-negative integers nums and an integer target. Put a sign, + or -, in front of every number in nums, keeping them in their order, and add the signed numbers up.
Count how many of the possible sign patterns give exactly target, and return that count. Two patterns are different when at least one position gets a different sign, even if the numbers at those positions are equal.
The three patterns are +3 - 1 + 2 - 2, +3 - 1 - 2 + 2 and -3 + 1 + 2 + 2. The first two differ only in which 2 is subtracted, and they still count separately.
-4 + 0 + 1 and -4 - 0 + 1 both give -3. A 0 can take either sign without changing the sum, so it doubles the count.
The only sums you can make are 5 and -5.
Constraints
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums) <= 1000-1000 <= target <= 1000Split the numbers into the group that gets + and the group that gets -. If the plus group sums to P and the whole array to S, the minus group sums to S - P. What does P have to be for the result to equal target?
Every number gets one of two signs, so n numbers have 2ⁿ sign patterns. Trying them all is the obvious plan, and at n = 20 that is about a million patterns. That is small enough to run, but it repeats work: two different patterns for the first ten numbers that land on the same partial sum have exactly the same future. Whatever signs the other ten numbers take, both patterns end up at the same totals.
Time O(n · S)Space O(S)
The full walkthrough and code are part of Premium
3