Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3052
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  日久生厌
    2020-11-21 07:22

    @KeithBeller's answer with slightly changed variable names and some comments.

        public static void Main(string[] args)
        {
            List input = new List() { 3, 9, 8, 4, 5, 7, 10 };
            int targetSum = 15;
            SumUp(input, targetSum);
        }
    
        public static void SumUp(List input, int targetSum)
        {
            SumUpRecursive(input, targetSum, new List());
        }
    
        private static void SumUpRecursive(List remaining, int targetSum, List listToSum)
        {
            // Sum up partial
            int sum = 0;
            foreach (int x in listToSum)
                sum += x;
    
            //Check sum matched
            if (sum == targetSum)
                Console.WriteLine("sum(" + string.Join(",", listToSum.ToArray()) + ")=" + targetSum);
    
            //Check sum passed
            if (sum >= targetSum)
                return;
    
            //Iterate each input character
            for (int i = 0; i < remaining.Count; i++)
            {
                //Build list of remaining items to iterate
                List newRemaining = new List();
                for (int j = i + 1; j < remaining.Count; j++)
                    newRemaining.Add(remaining[j]);
    
                //Update partial list
                List newListToSum = new List(listToSum);
                int currentItem = remaining[i];
                newListToSum.Add(currentItem);
                SumUpRecursive(newRemaining, targetSum, newListToSum);
            }
        }'
    

提交回复
热议问题