Possible Duplicate:
Algorithm to find which number in a list sum up to a certain number
question:
there is a list: [1,2,3,4,6,8,10,12], i want to use these numbers to sum up to a new number 16.
rules:
1) don’t need to use all of the numbers, 6 + 10 will be ok.
2) a number can use multi times, 12+2+1+1 will be ok.
3) order matters, 12 + 6 and 6 + 12 are two different combinations.
i have see algorithm to sum up a list of numbers for all combinations, but this is not the same.
don’t know much about algorithm, if this fit certain algorithm, please let me know, or some python code / pseudo-code will be much appreciated.
First – note that even finding if there is any subset that sums to the desired number is NP-Complete and is known as the subset sum problem, so there is no known polynomial solution for it.
Now, regarding the specific issue, here are some options:
First there is of course the obvious “generate all subsets and check the sum” way. Note that if your elements are all non-negative, you can use branch and bound and terminate a large portion of the possibilities before you actually develop them (If you found a subset
Xwithsum(X) == s, and you are looking for the numbern < s– you can be sure any set containingXwill NOT find the solution). Something along the lines of:Invoke with
findSubsets(list,[],n)wherelistis your list of items,nis the desired number and[]is an empty list.Note that it can be easily parallelized if needed, there is no real syncrhonization needed between two subsets explored.
Another alternative if the list contains only integers is using Dynamic Programming for solving the subset sum problem. Once you have the matrix you can re-create all the elements from the table by going back in the table. This similar question discusses how to get a list from the knapsack DP solution. The principles of the two problems are pretty much the same.