# Combination sum in C# with recursive approach

• I tried a recursive approach with C#:

``````public class Solution {

int ListSum(IList<int> list)
{
int sum = 0;

foreach (int myInt in list)
{
sum += myInt;
}

return sum;
}

public IList<IList<int>> CombinationSumHelper(int[] candidates, int candidatePointer, int target, IList<int> combination, IList<IList<int>> combinations)
{

if (target == ListSum(combination))
{
return combinations;
}

if (candidatePointer > candidates.Length - 1)
{
return combinations;
}

if (ListSum(combination) + candidates[candidatePointer] <= target)
{
List<int> newList = new List<int>(combination);
combinations = CombinationSumHelper(candidates, candidatePointer, target, newList, combinations);
}

candidatePointer++;

if (combination.Count > 0)
{
combinations = CombinationSumHelper(candidates, candidatePointer, target, combination, combinations);
}

return combinations;
}

public IList<IList<int>> CombinationSum(int[] candidates, int target)
{
IList<IList<int>> combinations = new List<IList<int>>();

for (int count = 0; count < candidates.Length; count++)
{
combinations = CombinationSumHelper(candidates, count, target, new List<int>(), combinations);
}

return combinations;
}

}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.