简体   繁体   中英

Finding the Minimal Set That Sum to a Given Number in an Array of Integers

Given the sum s and an array of positive integers, find the minimal subset whose elements add up to s. For example, given the array {1,2,3,4,5} and the sum s = 8, the minimal subset would be {3,5}.

So far I can solve for a set of integers that add up to the array with the greedy approach using recursion, but I can't find how to find the minimum subset. Is there a specific algorithm I should research?

This is the "zero-one equality knapsack problem." It is NP-complete. However, a variety of effective algorithms for the problem exist.

  1. If the sum is small enough to allocate that many bits of memory and iterate over them n (number of array elements) times, you can use dynamic programming.

  2. Mixed-integer program solvers like CPLEX, Gurobi, and SCIP will often do fairly well on "typical" instances that are likely to arise in practice. Some care needs to be taken when formulating knapsack problems as input to MIP solvers to avoid precision issues.

  3. If you can tolerate some imprecision: Polynomial-time approximation schemes for inequality knapsack (where you want the smallest set of numbers summing to something at most s) exist and aren't too hard to describe: Scale all of the numbers involved down to something where you can do dynamic programming and deal with the result. You can use the same approach to get approximate solutions to equality knapsack if you take care to accept near-solutions to the approximate problem as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM