Possible Duplicate:
Algorithm: Extract subset based on property sum
in the simple case we have an array:
{6, 1, 3, 11, 2, 5,12}
and we want to know all combinations the sum of elements contained in that array to getting 12.
in this case we will get four combinations:
- 12
- 1 + 11
- 6 + 5 + 1
- 1 + 3 + 2 + 6
so, how can we do this in BASIC or PHP?. maybe pseudo-code first ;-).
I’ve been looking but there just got a combination with a predetermined number of elements.
The problem is NP-Hard. Even determining if there is ANY subset of the problem that sums to the desired number is NP-Hard (known as the subset sum problem), and there is no known polynomial solution to it.
Thus, you should look for an exponantial solution, such as a backtracking one – generate all possible combinations, and check if they are valid.
You can use trimming to get your search faster (for example, if you generate a partial subset of sum 13, no need to check other subsets which are supersets of this subset, since they will definetly won’t lead to a solution.
pseudo code:
Complexity is
O(2^n)– need to generate at worst case all 2^n possible subsetsInvoke with
findValidSubsets(desiredSum,myArray,0,[]), where[]is an empty initial list