C#算法 - 寻找最少数量的必要对象算法、必要、数量、对象

2023-09-11 22:41:49 作者:悲哀寸步不离

让我们说我有以下的code。

Let's say I have the following code.

var numberToGetTo = 60; 
var list = new[] {10, 20, 30, 40, 50};

我希望能够回到50安培; 10从列表中= 60。

I want to be able to return 50 & 10 from list to = 60.

如果该numberToGetTo 100我想回到50,50。

If the numberToGetTo was 100 I would want to return 50, 50.

如果该numberToGetTo是85我想回到50,40。

If the numberToGetTo was 85 I would want to return 50, 40.

我想从必要去了numberToGetTo列表返回最少的数字,而住最接近(等于或greather),而不是它。

I want to return the least amount of numbers from the list necessary to get to the "numberToGetTo", while staying closest (equal or greather) than to it.

在做这样的事情的LINQ可能吗?

Is doing something like this with Linq possible?

推荐答案

这是一个NP完全问题称为背包问题。这意味着,你最好的方法是不是要在多项式时间。您可能需要暴力破解的解决方案。

This is an NP-complete problem called the knapsack problem. That means, that your best method is not going to be in polynomial time. You may have to brute-force a solution.