using System; using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var packSizes = new int[] { 5, 8, 10, 25, 50 }; var totalNeeded = 176; var result = GeneratePackings(packSizes, totalNeeded); Console.WriteLine(result.Count()); var maximal = result.Where (r => r.Zip(packSizes, (a, b) => a * b).Sum() == totalNeeded).ToList(); var min = maximal.Min(m => m.Sum()); var minPacks = maximal.Where (m => m.Sum() == min).ToList(); foreach (var m in minPacks) { Console.WriteLine("{ " + string.Join(", ", m) + " }"); } } // Define other methods and classes here public static List GeneratePackings(int[] packSizes, int totalNeeded) { var packings = GeneratePackingsInternal(packSizes, 0, new int[packSizes.Length], totalNeeded); return packings; } private static List GeneratePackingsInternal(int[] packSizes, int packSizeIndex, int[] packCounts, int totalNeeded) { if (packSizeIndex >= packSizes.Length) return new List(); var currentPackSize = packSizes[packSizeIndex]; var currentPacks = new List(); if (packSizeIndex + 1 == packSizes.Length) { var lastOptimal = totalNeeded / currentPackSize; packCounts[packSizeIndex] = lastOptimal; return new List { packCounts }; } for (var i = 0; i * currentPackSize <= totalNeeded; i++) { packCounts[packSizeIndex] = i; currentPacks.AddRange(GeneratePackingsInternal(packSizes, packSizeIndex + 1, (int[])packCounts.Clone(), totalNeeded - i * currentPackSize)); } return currentPacks; } }