问题
Lets say you have a list of 8 prices - for example:
1$
2$
3$
4$
5$
6$
7$
8$
You want to divide the prices into 2 groups of 4 prices each.
Let the total price of a group be the sum of the individual prices of the group. How do you divide the group such that the difference between the two total prices is as small as possible?
The obvious solution is to try all the pairs and see which is the lowest, but is there a more efficient solution that could work if this were extended to more than 8 prices or more than 2 groups?
回答1:
Looks really innocent, but it's a super hard problem.
The obvious solution is to try all the pairs and see which is the lowest, but is there a more efficient solution that could work if this were extended to more than 8 prices or more than 2 groups?
As long as P != NP: No, generally there is no efficient (polynomial) solution. And the obvious solution (AKA brute-force) has exponential complexity.
Let N = number of prices and K = number of subsets.
Partition problem for K=2 is already NP-complete. So, generalized version is also NP-complete. If one would found an efficient (polynomial) algorithm, that would mean that P = NP.
You can try with sub-optimal solutions, they will be much faster, but without a gurantee of optimal solution. For K=2 Wikipedia describes pseudo-polynomial time dynamic programming algorithm. For K>2:
The 3-partition problem is quite different than the Partition Problem and has no pseudo-polynomial time algorithm unless P = NP. For generalizations of the partition problem, see the Bin packing problem.
来源:https://stackoverflow.com/questions/21056592/minimizing-the-difference-between-sums