The problem of a subset of sums is a well-known NP-complete problem. Here I am going to suggest that you are looking for any set of numbers to sum with a goal (if you are really looking for only two numbers, there is a five-line solution using a hash counting table that works in O (n)).
There are two main approaches. The first is just to check every possible subsequence. As you already noticed, this takes O (2 n ) time (exponential), which is unsolvable if n is 1000.
Secondly, to track what amounts can be obtained from the list prefixes. This is a very simple approach and works well if integers are limited. As an example, if the input is n k-bit integers, it has computational complexity O (2 k n 2 ) (pseudo-polynomial): the largest sums can get 2 k n, so the table has no more than 2 k n 2 entries. This is a typical approach to dynamic programming, where the subtask T[s][k] = (A[1..k] has a subsequence summing to s) , and the final solution is given by T[target][n] .
Here's a solution in Python that implements this:
def subset_sum(A, target): T = {0} # T[s][0] = (TRUE iff s == 0) for i in A: T |= {x + i for x in T} return target in T
Examples:
>>> subset_sum([-5,6,7,1,0,12,5,-6,100], 13) True >>> subset_sum([95, -120, 22, 14491], 13) False
Bonus: if you are interested, here is a solution to the problem of a couple of sums. It starts in O (n) time and tells you if the array has two numbers summed for the purpose.
from collections import Counter def pair_sum(A, t): C = Counter(A) for k,v in C.iteritems(): if t == k+k and v > 1: return True
Examples:
>>> pair_sum([3,3,3,4], 13) False >>> pair_sum([3,3,3,10], 13) True >>> pair_sum([7,7,2], 14) True >>> pair_sum([7,14,2], 14) False