问题
I have a set of numbers eg. [100,90,80,70,60,50]
and want to find all combinations of size r=3
but in order of decreasing sum.
Arranging the numbers in decreasing order does not work eg.
(100, 90, 80) 270
(100, 90, 70) 260
(100, 90, 60) 250
(100, 90, 50) **240**
(100, 80, 70) **250**
(100, 80, 60) 240
How can i go about finding such a combination set with decreasing sum value.
回答1:
Here' the Code
import itertools
array = [100,90,80,70,60,50]
size = 3
answer = [] # to store all combination
order = [] # to store order according to sum
number = 0 # index of combination
for comb in itertools.combinations(array,size):
answer.append(comb)
order.append([sum(comb),number]) # Storing sum and index
number += 1
order.sort(reverse=True) # sorting in decreasing order
for key in order:
print key[0],answer[key[1]] # key[0] is sum of combination
Output for the above code is
270 (100, 90, 80)
260 (100, 90, 70)
250 (100, 80, 70)
250 (100, 90, 60)
240 (90, 80, 70)
240 (100, 80, 60)
240 (100, 90, 50)
230 (90, 80, 60)
230 (100, 70, 60)
230 (100, 80, 50)
220 (90, 70, 60)
220 (90, 80, 50)
220 (100, 70, 50)
210 (80, 70, 60)
210 (90, 70, 50)
210 (100, 60, 50)
200 (80, 70, 50)
200 (90, 60, 50)
190 (80, 60, 50)
180 (70, 60, 50)
回答2:
The first (and naive) solution is to iterate over all posible permutations, and save those sets in a min-heap. At the end just remove all sets one by one.
run time: suppose x = n choose r, so O(xlogx)
The second one is a little more complicated:
* You need to save the minimum number you found out untill now
* now you are iterating exactly like your example with one change, to know what is the next set you are moving to, you have to replace every number in the current set with the next number in the array, and replace the max option that less than the minimum you are saving. and of course set the minimum to the new minimum.
run time: O((n choose r)*r)
来源:https://stackoverflow.com/questions/44405057/find-combinations-of-size-r-from-a-set-with-decreasing-sum-value