0

I want to count the subsets of a with k subset elements which sum to n. The possible subset elements are defined through a given array a with distinct positive elements. Possible subset elements can be just choosen once per subset. How Can i do this? Optimal without iterating through all subsets.

Example:

n := 10

k := 3

a := 1,2,6,7,8

=> 1 ( 1,2,7 )

TTho Einthausend
  • 609
  • 4
  • 13
  • 1
    Seems you already know about dynamic programming. So apply it. Your last questions resemble homeworks without any attempts to solve. – MBo Feb 20 '20 at 17:36
  • *branch-and-bound* Dead easy. But make sure you start at the large end of `a` so you can take full advantage of what you know about its contents. That is, given that the largest element is `8` and that all elements are distinct and positive, the sum of the two smallest elements is at least `3`. – High Performance Mark Feb 20 '20 at 17:38
  • Yes but then iam kind of iterating through the combinations which is roughly O(n^k or k^n?). I through it can be solved with better complexity. – TTho Einthausend Feb 20 '20 at 17:46
  • Theoretically, yes, horrid complexity. In practice, it's generally a different matter but exactly how different depends on the examples you have to solve. – High Performance Mark Feb 20 '20 at 17:57

1 Answers1

2

Make a table A of size (n+1)*(k+1) or map with pair of integers as key.

Entry A[i][j] will contain number of variants to make sum i from j elements

You need to compose value n from k elements, so A[n][k] might be built from A[n-v][k-1] where v is any value from given set.

After filling the table A[n][k] is answer

MBo
  • 77,366
  • 5
  • 53
  • 86
  • This is what I consider a good answer for a question like this -- sketching the solution and the important points, and not spelling it all out. – Robert Dodier Feb 20 '20 at 19:19