【发布时间】:2021-10-24 19:12:02
【问题描述】:
我有一个目标号码和一个号码列表。我需要从列表中找到一个组合,它们的总和是目标数。
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。
如何编辑此方法以更快、更智能地完成工作?
【问题讨论】:
标签: c#