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
@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);
}
}'