here is how i call the following function:
List<decimal> numbers = new List<decimal>();
numbers.Add(210m);
numbers.Add(188.83m);
numbers.Add(67.93m);
numbers.Add(125.92m);
numbers.Add(35.92m);
numbers.Add(19.16m);
numbers.Add(98.48m);
List<decimal> listresult = FindSumSubset(9075.12m, numbers);
************the function*
List<decimal> FindSumSubset(decimal sum, List<decimal> list)
{
for (int i = 0; i < list.Count开发者_StackOverflow; i++)
{
decimal value = list[i];
if (sum - value == 0.0m)
{
return new List<decimal> { value };
}
else
{
var subset = FindSumSubset(sum - value, list.GetRange(i + 1, list.Count-1 -i));
if (subset != null)
{
subset.Add(value);
return subset;
}
}
}
return null;
}
when i run in debug mode, the decimal sum
is giving me a huge negative value like -93435.34
how can this be happening?
Try making this change:
if (sum - value <= 0.0m)
The problem is that sum-value is not exactly 0 so it just keeps recursing forever.
Also, I think you want to remove the for
loop. You don't need it if you recurse.
You're overflowing and not checking is my guess.
精彩评论