簡體   English   中英

查找加起來等於或大於 X 的數字集組合的算法

[英]Algorithm to find combinations of sets of numbers that add up to equal or greater than X

所以我試圖解決的問題是我想在我擁有的集合中找到可能的數字組合,這些組合加起來為 400

我在第 1 組中有 6 個數字,它們可以是以下任何一個:[0, 6, 8, 12, 16, 30] 和第 2 組中的另外 6 個數字,它們可以是以下任何一個:[0, 16, 20, 25, 32, 40, 50]

我認識到,因為我所關心的只是總和,所以順序應該無關緊要,但我不確定我實際上會如何進行設置。 一次改變 1 個數字,每次迭代減少值,然后一旦我達到總數低於 400,打破該運行並移動到下一個數字是否有意義? 例如:如果我從 [30,30,30,30,30,30][50,50,50,50,50,50] 開始減少最后一個索引,一旦我點擊 [30,30,30,30 ,30,30][50,50,50,32,20,16] 其余的迭代集中在第 11 列(只有一列,當它等於 16 時)可以忽略,因為它們只會減少。 或者有沒有更合乎邏輯的方法來解決這個問題?

您可以訂購兩組,為第一組中的每個 num 設置一個循環,然后將其與第二組中的每個 num 相加,但是一旦您的總和未能超過 400,您就可以停止。

就像是

numbers_whose_sums_are_bigger_than_the_number_in_question = []
for x in ordered_set_a: 
    sum = 401
    while sum > 400:
        for y in ordered_set_b:
            sum = x + y
            if sum > 400:
                numbers_whose_sums_are_bigger_than_the_number_in_question.append([x,y])
print(numbers_whose_sums_are_bigger_than_the_number_in_question)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM