I have a given number of integers in an array. Let's say: {1, 2, 3, 4, 5, 6, 7 }. Note this is just an example they might not be consecutive numbers.
I need to find the numbers that are satisfying the following conditions:
- The numbers have a set sum.
- The count of the numbers should be specified.
So with the given numbers above:
- If the sum is 7 and the number count is 2 it should output {1, 6}.
- If the sum is 7 and the number count is 3 it should output {1, 2, 4}.
- If the sum is 7 and the number count is 1 it should output {7}.
I found out similar thread: algorithm to find the correct set of numbers. However the algorithms there doesn't have the requirement for specifying the number count. Here is the algorithm thanks to Lajos Arpad:
public static List<int> backtrack(List<int> currentNumbers, int[] numbers, int depth, int targetValue, int j)
{
for (int i = j; i < numbers.Length; i++)
{
int potentialSolution = numbers[i];
if (currentNumbers.Sum() + potentialSolution > targetValue)
{
continue;
}
else if (currentNumbers.Sum() + potentialSolution == targetValue)
{
/*Store solution*/
currentNumbers.Add(potentialSolution);
return currentNumbers;
}
else
{
currentNumbers.Add(potentialSolution);
return backtrack(currentNumbers, numbers, depth + 1, targetValue, i + 1);
}
}
return null;
}
Can someone please help me to modify it to add the extra numbers count condition?