C# algorithm - find least number of objects necessary

后端 未结 6 1107
孤街浪徒
孤街浪徒 2021-01-14 03:19

Let\'s say I have the following code.

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

I want to be able to return 50 &

6条回答
  •  忘掉有多难
    2021-01-14 04:08

    Here's an implementation that uses Linq to be as clean as possible. It makes no attempt to optimize for performance over large inputs.

    I'm assuming that you wouldn't use this algorithm for large inputs anyway, since the problem is NP-Complete, and therefore clarity is the right goal. My algorithm is O(n^2), and recursive at that.

        static IEnumerable Knapsack(IEnumerable items, int goal)
        {
            var matches = from i in items
                          where i <= goal
                          let ia = new[] {i}
                          select i == goal ? ia : Knapsack(items, goal - i).Concat(ia);
    
            return matches.OrderBy(x => x.Count()).First();
        }
    

提交回复
热议问题