I have an array of integers and need to apply a variant of the subset sum algorithm on it, except that instead of finding a set of integers whose sum is 0 I am trying to find a set of integers whose sum is n
. I am unclear as to how to adapt one of the standard subset sum algorithms to this variant and was hoping for any insight into the problem.
Subset sum variant with a non-zero target sum
698 views Asked by Kuker At
2
There are 2 answers
3
On
You can solve this by using dynamic programming.
Lets assume that:
N
- is the sum that required (your first input).M
- is the number of summands available (your second input).- a1...aM - are the summands available.
f[x]
istrue
when you can reach the sum ofx
, andfalse
otherwise
Now the solution:
Initially f[0] = true
and f[1..N] = false
- we can reach only the sum of zero without taking any summand.
Now you can iterate over all ai, where i
in [1..M], and with each of them perform next operation:
f[x + ai] = f[x + ai] || f[x], for each x in [M..ai] - the order of processing is relevant!
Finally you output f[N].
This solution has the complexity of O(N*M), so it is not very useful when you either have large input numbers or large number of summands.
This is subset sum problem, which is NP-Complete (there is no known efficient solution to NP-Complete problems), but if your numbers are relatively small integers - there is an efficient pseudo polynomial solution to it that follows the recurrence:
Later, you need to step back on your choices, see where you decided to "reduce" (take the element), and where you decided not to "reduce" (not take the element), on the generated matrix.
This thread and this thread discuss how to get the elements for similar problems.
Here is a python code (taken from the thread I linked to) that does the trick.
If you are not familiar with python - read it as pseudo code, it's pretty easy to understand python!.