There are several ways to solve this problem. One of them is the classic DP solution that others have posted. I am going to post a solution that uses only O (S) memory, where S is the sum of all the integers in the array (can be changed to denote the desired amount), and another that uses a very efficient randomized algorithm that can be tested to be very fast even for hundreds of thousands of numbers of any size and even rational and negative numbers.
DP solution in time O (nS) and O (S):
Pseudo-code for a randomized algorithm: Let Used Used = list of numbers that you sum. Let Unused = a list of numbers you DO NOT summarize. Let tmpsum = 0. Let S = the desired amount that you want to achieve.
for ( each number x you read ) toss a coin: if it heads and tmpsum < S add x to Used else add x to Unused while ( tmpsum != S ) if tmpsum < S MOVE one random number from Unused to Used else MOVE one random number from Used to Unused print the Used list, containing the numbers you need to add to get S
It will be much faster than a dynamic programming solution, especially for random inputs. The only problems are that you cannot reliably detect when there is no solution (you can let the algorithm work for several seconds, and if it does not end, suppose there is no solution) and you cannot be sure that you will get the solution with minimum number of items selected. Again, you can add some logic to keep the algorithm going and trying to find a solution with fewer elements until certain stopping conditions are met, but that will make it slower. However, if you are only interested in a working solution, and you have a lot of numbers, and the desired amount can be VERY large, this is probably better than the DP algorithm.
Another advantage of this approach is that it will also work for negative and rational numbers without any changes, which is not true for the DP solution, since the DP solution involves the use of partial sums as array indices, and the indices can be natural numbers. Of course, you can use hashtables, but that will make the DP solution even slower.
To generate all combinations, you should look for backtracking: http://en.wikipedia.org/wiki/Backtracking
For this problem you need to use something like this:
void back(int k) { if ( k > numElements ) {
You must run it on paper for a small number of elements to see how it works. You can optimize it by calculating the amount when you go, thereby avoiding the final summation. This is a general idea.