I read through all subset sum topics and still have issues with implementing the algorithm for the following problem.
Given the array A of N integers (N<=20) where
- a[i]<=20
- values do not have to be unique
and an integer K (K<=20).
Rules:
- Array items equal to K are "covered" with K.
- If sum of two or more array numbers is equal to K, these numbers are also covered.
- Each number in the array can be covered only once.
Example:
N=6, integers: 1, 1, 2, 3, 4, 5
K=4
Possible coverages:
- coverage
- 4 is covered.
- 1, 1, 2 are covered as 1+1+2=4.
- coverage
- 4 is covered.
- 1, 3 are covered as 1+3=4.
K=5
Possible coverages:
- coverage
- 5 is covered.
- 1,1,3 are covered as 1+1+3=5.
- coverage
- 5 is covered.
- 1,4 are covered as 1+4=5.
- 2,3 are covered as 2+3=5.
Goal:
For given array A and integer K, find all possible "coverages". I need all coverages, not only one which covers most of the array items.
I have tried with two approaches:
- Brut force algorithm. Checking all possible subsets of all possible sizes works, but takes too much time even for only 10 numbers. I need it to finish in no more than 500ms.
- First, I sorted the array in descending order. Then for each possible number of sub-sums I create "slots". I loop through the array and put numbers in the slots following the rules like:
- Put number in the slot if its sum becomes equal to K.
- Put number in the slot having the least sum of all slots.
- Put number in the slot which gives the closet sum to K of all slots.
Well, the second approach works and works fast. But I found scenarios where some coverages are not found.
I would appreciate if somebody offered idea for solving this problem.
I hope I explained the problem well.
Thanks.