【问题标题】:Get Numbers Combination to a Target Sum - C#获取数字组合到目标总和 - C#
【发布时间】: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#


    【解决方案1】:

    如果我有足够的声誉可以发表评论,那么我会的。您的问题可能已经得到解答(您要查找的内容称为排列)。就性能而言,您希望限制执行的迭代次数。这是另一个应该回答您问题的 stackoverflow 问题的链接:

    How to find out all permutations of numbers that sum to 100

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多