簡體   English   中英

有沒有一種算法,給定一個整數列表,返回一個大小為 N 的整數列表,其中總值為 V±100?

[英]Is there an algorithm that, given a list of integers, returns a list of integers of size N where the total value is V±100?

給定一個整數列表,我如何能夠返回一個大小為 N的整數列表,其中整數的總和等於 V±100

例如,如果我有一個整數list = [652, 840, 585, 147, 652, 576, 786, 362, 800, 591] ,我如何返回一個大小為 21且總值介於11,500 和 11,700因為V = 11,600N = 21 在這種情況下,可以多次重復 integer。

我試着用谷歌搜索,但找不到我要找的東西。

我更喜歡 JavaScript 中的解決方案,但任何語言都可以。

解決這個問題的想法類似於子集和問題的動態規划解決方案。

我不會給你代碼。 但我會給你確切的方法。

“100以內”是一條紅鯡魚。 你最好簡單地選擇“最接近”。 然后驗證您是否在目標的 100 范圍內得到答案。 (碰巧,在這種情況下,您可以在鼻子上達到目標總和。)

這個想法是,對於n in 0..N ,您想要構建一個數據結構映射值,您可以使用n整數將值映射到可以到達那里的路徑。 對於n=0這很容易 - 您的數據結構只是{0: null} (你可以用一個空的總和得到 0。)

對於n=1 ,您最終會得到一個數據結構,其中包含840: [840, [null]]類的條目。

對於n=2 ,您最終會得到一個數據結構,其中包含1680: [840, [840, [null]]]類的條目。

當您達到n=21時,您可以使用以下方法提取最接近的解決方案:

let bestValue = null;
Object.keys(solution).forEach(function (value) {
    if (bestValue == null) {
        bestValue = value*1; // The *1 casts a string to a number.
    }
    else if (Math.abs(targetSum - value) < Math.abs(targetSum - bestValue)) {
        bestValue = value*1;
    }
});

let bestSolution = solution[bestValue];

// We have the bestSolution as a linked list.  Recover it as an array.
let answer = [];
while (bestSolution) {
    answer.push(bestSolution[0]);
    bestSolution = bestSolution[1];
}

在您的具體解決方案中,最終答案將類似於:

[
  147, 147, 147, 147, 147,
  147, 147, 147, 652, 652,
  800, 800, 800, 840, 840,
  840, 840, 840, 840, 840,
  840
]

暫無
暫無

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

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