... the original problem statement may be converted into the following subset sum problem: find the number of ways to gather a subset of nums
such that its sum is equal to (target + sum(nums)) / 2
.
We can also add another trivial check to our algorithm: if target + sum(nums)
is not divisible by 2, we can return 0 because there is no solution (this follows from the last line in our derivation above).
Therefore, the crux of this reformulated problem statement is (in pseudo-code):
xxxxxxxxxx
for the set of values up to some value V in nums:\
for some target sum S:\
number of ways to attain S =
number of ways to attain S without V\
+ number of ways to attain S-V with V
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment