Following from these question Subset sum problem and Sum-subset with a fixed subset size I was wondering what the general algorithm for solving a subset sum problem, where we are forced to use EXACTLY k integers, k <= n.
Evgeny Kluev mentioned that he would go for using optimal for k = 4 and after that use brute force approach for k- 4 and optimal for the rest. Anyone could enlight what he means by a brute force approach here combined with optimal k=4 algo?
Perhaps someone knows a better, general solution?
The original dynamic programming algorithm applies, with a slight extension – in addition to remembering partial sums, you also need to remember number of ints used to get the sums.
In the original algorithm, assuming the target sum is
Mand there arenintegers, you fill a booleannxMarrayA, whereA[i,m]is true iff summcan be achieved by picking (any number of) from firsti+1ints (assuming indexing from 0).You can extend it to a three dimensional array
nxMxk, which has a similar property –A[i,m,l]is true iff, summcan be achieved by picking exactlylfrom firsti+1ints.Assuming the ints are in array
j[0..n-1]:The recursive relation is pretty similar – the field
A[0,j[0],1]is true (you pickj[0], getting sumj[0]with 1 int (duh)), other fields inA[0,*,*]are false and deriving fields inA[i+1,*,*]fromA[i,*,*]is also similar to the original algorithm:A[i+1,m,l]is true ifA[i,m,l]is true (if you can pickmfrom firstiints, then obviously you can pickmfrom firsti+1ints) or ifA[i, m - j[i+1], l-1]is true (if you pickj[i+1]then you increase the sum byj[i+1]and the number of ints by 1).If
kis small then obviously it makes sense to skip all of the above part and just iterate over all combinations ofkints and checking their sums.k<=4indeed seems like a sensible threshold.