How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?
A brief example:
- Set of numbers to add:
N = {1,5,22,15,0,...} - Desired result:
12345
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This problem can be solved with a recursive combinations of all possible sums filtering out those that reach the target. Here is the algorithm in Python:
This type of algorithms are very well explained in the following Stanford’s Abstract Programming lecture – this video is very recommendable to understand how recursion works to generate permutations of solutions.
Edit
The above as a generator function, making it a bit more useful. Requires Python 3.3+ because of
yield from.Here is the Java version of the same algorithm:
It is exactly the same heuristic. My Java is a bit rusty but I think is easy to understand.
C# conversion of Java solution: (by @JeremyThompson)
Ruby solution: (by @emaillenin)
Edit: complexity discussion
As others mention this is an NP-hard problem. It can be solved in exponential time O(2^n), for instance for n=10 there will be 1024 possible solutions. If the targets you are trying to reach are in a low range then this algorithm works. So for instance:
subset_sum([1,2,3,4,5,6,7,8,9,10],100000)generates 1024 branches because the target never gets to filter out possible solutions.On the other hand
subset_sum([1,2,3,4,5,6,7,8,9,10],10)generates only 175 branches, because the target to reach10gets to filter out many combinations.If
NandTargetare big numbers one should move into an approximate version of the solution.