Here is an algorithm: to find a solution for one element in A.
Sort the elements in B.
Let's create a function called SumTo( int n )
which should return a set of elements from B that sum to the value or a failure code.
Start by finding the highest element that is <= n. If it is equal we have a solution. If it is less (say m ) then call SumTo( n - m ) then add our element to the result if we don't get a failure.
If we do get a failure then go to the next element < m and try again.
The only issue is that we probably can't use the same element more than once so we may need that in our SumTo algorithm. In any case we find our elements in reverse order.
For caching purposes we might want to store the sum of all the elements up to a point within B.
I could probably code this easily enough in C++ using STL.
If multiple solutions exist though it may be necessary to choose one over another one so you can complete all the elements in A. Eg:
A = { 15, 21, 25 }
B = { 6, 7, 8, 9, 12, 19 }
15 must be made with 7+8 to keep the 6 and the 9 free for the other numbers, and not with 6+9.