我们每天会有一些涉及 IT 技术的付款(Transaction
)进入我们的公司。每个 Transaction
都有一个 ID
和一个 Amount
。我们需要将其中的一些交易与特定金额相匹配。例如:
Transaction Amount
1 100
2 200
3 300
4 400
5 500
如果我们想找到加起来为600的交易,你需要一些集合(1,2,3),(2,4),(1,5)。
我找到了一个算法,并进行了改进,如下所示。对于30个交易,它只需要15毫秒。但是,交易数量平均约为740,最大接近6000。有没有更有效的方法来执行这个搜索?
sum_up(TransactionList, remittanceValue, ref MatchedLists);
private static void sum_up(List<Transaction> transactions, decimal target, ref List<List<Transaction>> matchedLists)
{
sum_up_recursive(transactions, target, new List<Transaction>(), ref matchedLists);
}
private static void sum_up_recursive(List<Transaction> transactions, decimal target, List<Transaction> partial, ref List<List<Transaction>> matchedLists)
{
decimal s = 0;
foreach (Transaction x in partial) s += x.Amount;
if (s == target)
{
matchedLists.Add(partial);
}
if (s > target)
return;
for (int i = 0; i < transactions.Count; i++)
{
List<Transaction> remaining = new List<Transaction>();
Transaction n = new Transaction(0, transactions[i].ID, transactions[i].Amount);
for (int j = i + 1; j < transactions.Count; j++) remaining.Add(transactions[j]);
List<Transaction> partial_rec = new List<Transaction>(partial);
partial_rec.Add(new Transaction(n.MatchNumber, n.ID, n.Amount));
sum_up_recursive(remaining, target, partial_rec, ref matchedLists);
}
}
假设已经定义了Transaction
:
class Transaction
{
public int ID;
public decimal Amount;
public int MatchNumber;
public Transaction(int matchNumber, int id, decimal amount)
{
ID = id;
Amount = amount;
MatchNumber = matchNumber;
}
}
c#
)。如果您遇到错误(不工作的代码)或遇到问题(性能),则Stackoverflow很好。我不是在坚持,但我认为您可以使用更好的算法。另一件事是您没有解释自己的算法,但它看起来像直接的(递归迭代),这是内存高效但性能较差的算法。 - Sinatr