Example #1
0
        private static int NumberOfShortestCombinations(int[] list, int initialGoal)
        {
            var memo    = new SimpleMemo <ulong>();
            var lengths = new SafeDictionary <int, int>();

            Explore(list.Length, 0, initialGoal);
            var shortestCombinations = lengths.OrderBy(x => x.Key).First().Value;

            return(shortestCombinations);

            void Explore(int size, uint pickmask, int goal)
            {
                if (goal == 0)
                {
                    var len = pickmask.NumberOfSetBits();
                    lengths[len]++;
                    return;
                }

                if (goal < 0 || size == 0)
                {
                    return;
                }

                if (memo.IsSeenBefore((ulong)size << 32 | pickmask))
                {
                    return;
                }

                // For skipped item, pass 0 into the bit-mask (ie do nothing); for used item pass 1.
                Explore(size - 1, pickmask << 1, goal);
                Explore(size - 1, (pickmask << 1) + 1, goal - list[size - 1]);
            }
        }