Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 从具有递减和值的集合中查找大小r的组合_Algorithm_Combinations_Combinatorics_Discrete Mathematics - Fatal编程技术网

Algorithm 从具有递减和值的集合中查找大小r的组合

Algorithm 从具有递减和值的集合中查找大小r的组合,algorithm,combinations,combinatorics,discrete-mathematics,Algorithm,Combinations,Combinatorics,Discrete Mathematics,我有一组数字,例如[100,90,80,70,60,50],我想找到所有大小的组合r=3,但按总和递减的顺序。 按降序排列数字不起作用 (100, 90, 80) 270 (100, 90, 70) 260 (100, 90, 60) 250 (100, 90, 50) **240** (100, 80, 70) **250** (100, 80, 60) 240 我怎样才能找到这样一个和值递减的组合集。第一个(也是最简单的)解决方案是迭代所有可能的置换,并将这些集合保存在最小堆中。最后,只需

我有一组数字,例如
[100,90,80,70,60,50]
,我想找到所有大小的组合
r=3
,但按总和递减的顺序。 按降序排列数字不起作用

(100, 90, 80) 270
(100, 90, 70) 260
(100, 90, 60) 250
(100, 90, 50) **240**
(100, 80, 70) **250**
(100, 80, 60) 240
我怎样才能找到这样一个和值递减的组合集。

第一个(也是最简单的)解决方案是迭代所有可能的置换,并将这些集合保存在最小堆中。最后,只需逐个删除所有集合。
运行时:假设x=n选择r,那么O(xlogx)

第二个比较复杂:
*您需要将找到的最小号码保存到现在

*现在,您的迭代与您的示例完全相同,只需进行一次更改,就可以知道要移动到的下一个集合是什么,您必须将当前集合中的每个数字替换为数组中的下一个数字,并替换小于正在保存的最小值的max选项。当然,将最小值设置为新的最小值。
运行时:O((n选择r)*r)

这里是代码

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
上述代码的输出为

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)

生成所有可能的子集并将其存储在中?为什么不?下一步必须小于或等于的条件将保证您将始终减少,并且所有选项的最大值将保证您不会错过任何选项“将当前集合中的每个数字替换为数组中的下一个数字”将跳过有效组合。我怀疑你的意思。但更换一个元件并不能保证找到下一个更小的组合。