1

An interesting variation of the subset sum problem was presented to me by a friend from work:

Given a set S of positive integers, of size n, and integers a and K, is there a subset R (of the set S) that contains exactly a elements, whose sum is equal to K?

He claims that this can be done with time complexity O(nka), I was unable to come up with a dynamic programming algorithm that achieved this running time. Can it be done?

ntsue
  • 2,325
  • 8
  • 34
  • 53

2 Answers2

3

It can be done if k and a are small enough, so that we can declare an array

bool found[a][k]

You would iterate over each value in S and iterate over every state in the found array to obtain a new state.

Say, for the indexes of a=1 and k = 7, and the current value from S being 7,

if found[1][7] is true, then you can also be sure that found[2][14] is also true.

When the iteration ends, all you need to do is check that [a][k] is true or not.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
  • Not sure that this approach meets the time complexity bound, since it looks like you have to iterate over subsets of S, not individual elements. – user486972 Nov 02 '10 at 15:54
  • Not really, I am iterating over elements of S and not subset. – Shamim Hafiz - MSFT Nov 03 '10 at 07:38
  • @ShamimHafiz What's the rationale for "if found[1][7] is true, then you can also be sure that found[2][14] is also true"? If you have {1, 2, 7} as the input set S, then found[1][7] is true but found[2][14] is false right? Subset can't take one element twice – Boyang Oct 19 '13 at 12:00
  • @CharlesW. You consider each element from S only once. If you were to code this up, the outermost loop would iterate over each value in S. – Shamim Hafiz - MSFT Oct 19 '13 at 21:30
3

Let S = {s1,\ldots,sn}

Let P(j,K,a) be true iff it is possible to find a elements in s1,\ldots,sj that sum up to K.

Then P(j,K,a) = P(j-1, K-sj, a-1) OR P(j, K, a) (either sj is needed or it is not needed).

The algorithm then consists of filling out 3-D table of dimension n by K+1 by a+1. Each entry takes constant time to fill, hence the time (and space) complexity is O(nKa)

user486972
  • 386
  • 1
  • 3