Given a set A
containing n
positive integers, how can I find the smallest integer >= 0 that can be obtained using all the elements in the set. Each element can be can be either added or subtracted to the total.
Few examples to make this clear.
A = [ 2, 1, 3]
Result = 0
(2 + 1 - 3)
A = [1, 2, 0]
Result = 1
(-1 + 2 + 0)
A = [1, 2, 1, 7, 6]
Result = 1
(1 + 2 - 1 - 7 + 6)
You can solve it by using Boolean Integer Programming. There are several algorithms (e.g. Gomory or branch and bound) and free libraries (e.g. LP-Solve) available.
Calculate the sum of the list and call it s. Double the numbers in the list. Say the doubled numbers are a,b,c. Then you have the following equation system:
Boolean x,y,z
a*x+b*y+c*z >= s
Minimize ax+by+cz!
The boolean variables indicate if the corresponding number should be added (when true) or subtracted (when false).
[Edit]
I should mention that the transformed problem can be seen as "knapsack problem" as well:
Boolean x,y,z
-a*x-b*y-c*z <= -s
Maximize ax+by+cz!
来源:https://stackoverflow.com/questions/5741242/subset-sum-problem-where-each-number-can-be-added-or-subtracted