Could C# Linq do combinatorics?

前端 未结 3 1171
死守一世寂寞
死守一世寂寞 2021-01-29 16:28

I have this data structure:

class Product
{
    public string Name { get; set; }
    public int Count { get; set; }
}

var list = new List(){ { Na         


        
3条回答
  •  梦毁少年i
    2021-01-29 16:59

    Judging from the comments you've left on other peoples' answers and your gist (link), it looks like what you're trying to solve is in fact the Knapsack Problem - in particular, the 0/1 Knapsack Problem (link).

    The Wikipedia page on this topic (that I linked to) has a short dynamic programming solution for you. It has pseudo-polynomial running time ("pseudo" because the complexity depends on the capacity you choose for your knapsack (W).

    A good preprocessing step to take before running the algorithm is to find the greatest common denominator (GCD) of all of your item weights (w_i) and then divide it out of each value.

    d <- GCD({w_1, w_2, ..., w_N})
    w_i' <- w_i / d //for each i = 1, 2, ..., N
    W' <- W / d //integer division here
    

    Then solve the problem using the modified weights and capacity instead (w_i' and W').

    The greedy algorithm you use in your gist won't work very well. This better algorithm is simple enough that it's worth implementing.

提交回复
热议问题