Question

Say you have some array with elements that you know are all positive, and smaller than a number N.

Can someone give me a general, high-level description of an algorithm to find out whether there is some subset within the array in which all the elements add up exactly to N?

It doesn't need to be particularly efficient; the set I'm working with is very small.

Was it helpful?

Solution

If efficiency is not important, an algorithm at a high-level is:

input: array A[1..K] of positive numbers, positive N

    for each subset S of { 1..K }
        sum = 0
        for each i in S
            sum = sum + A[i]
        end
        if (sum equals N) return true
    end
    return false

OTHER TIPS

Pseudocode. Extremely inefficient.

if empty(numbers) return false
return hasSumSubset(numbers, N)

boolean hasSumSubset(numbers[], N):
   p = pop(numbers)
   if empty(numbers) return N == p
   return hasSumSubset(numbers, N-p) or hasSumSubset(numbers, N)

If you actually implement this make sure numbers is copied (not passed in by ref) for the recursive calls; otherwise it won't work correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top