获取数字组合到目标和- c#

  • 本文关键字:目标 数字 组合 获取 c#
  • 更新时间 :
  • 英文 :


我有一个目标数字和一个数字列表。我需要从列表中找到一个组合,它们的和是目标数。

Example:
list = [1,2,3,10]
target = 12
result = [2,10]

下面是这样一个类:

public class Solver {
private List<List<decimal>> mResults;
public List<List<decimal>> Solve(decimal goal, decimal[] elements) {
mResults = new List<List<decimal>>();
RecursiveSolve(goal, 0.0m, 
new List<decimal>(), new List<decimal>(elements), 0);
return mResults; 
}
private void RecursiveSolve(decimal goal, decimal currentSum, 
List<decimal> included, List<decimal> notIncluded, int startIndex) {
if (mResults.Count > 0) return;
for (int index = startIndex; index < notIncluded.Count; index++) {
decimal nextValue = notIncluded[index];
if (currentSum + nextValue == goal) {
List<decimal> newResult = new List<decimal>(included);
newResult.Add(nextValue);
if (mResults.Count == 0)
mResults.Add(newResult);
else
break;
}
else if (currentSum + nextValue < goal) {
List<decimal> nextIncluded = new List<decimal>(included);
nextIncluded.Add(nextValue);
List<decimal> nextNotIncluded = new List<decimal>(notIncluded);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(goal, currentSum + nextValue,
nextIncluded, nextNotIncluded, startIndex++);
}
}
}
}

它将找到与目标数相加的第一个数字组合。但是当列表更大的时候,只要它容易找到,就需要花费很多时间来找到它的组合。这样的:

Target number is= 100;
list is:
90
0.56
10
and so many other numbers

它将90与0.56相加,所以它将是90.56,然后它将搜索到100,但只要90 + 10(索引0和2)将是100。

如何编辑这个方法来更快更智能地完成它的工作?

如果我有足够的声誉来评论,那么我就会评论。你的问题可能已经得到了答案(你所寻找的被称为排列)。就性能而言,您希望限制执行的迭代次数。下面是另一个stackoverflow问题的链接,可以回答你的问题:

如何找出总和为100的数字的所有排列