Sum array values with sum equals X

﹥>﹥吖頭↗ 提交于 2020-01-07 08:46:35

问题


I have an integer collection. I need to get all possibilites that sum of values are equal to X.

I need something like this.

It can be written in: delphi, c#, php, RoR, python, cobol, vb, vb.net


回答1:


That's a subset sum problem. And it is NP-Complete.

The only way to implement this would be generate all possible combinations and compare the sum values. Optimization techniques exists though.

Here's one in C#:

static class Program
{
    static int TargetSum = 10;
    static int[] InputData = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    static void Main()
    {
        // find all permutations
        var permutations = Permute(InputData);

        // check each permutation for the sum
        foreach (var item in permutations) {

            if (item.Sum() == TargetSum) {

                Console.Write(string.Join(" + ", item.Select(n => n.ToString()).ToArray()));
                Console.Write(" = " + TargetSum.ToString());
                Console.WriteLine();

            }
        }

        Console.ReadKey();
    }

    static IEnumerable<int[]> Permute(int[] data) { return Permute(data, 0); }

    static IEnumerable<int[]> Permute(int[] data, int level)
    {
        // reached the edge yet? backtrack one step if so.
        if (level >= data.Length) yield break;

        // yield the first #level elements
        yield return data.Take(level + 1).ToArray();

        // permute the remaining elements
        for (int i = level + 1; i < data.Length; i++) {
            var temp = data[level];
            data[level] = data[i];
            data[i] = temp;

            foreach (var item in Permute(data, level + 1))
                yield return item;

            temp = data[i];
            data[i] = data[level];
            data[level] = temp;
        }

    }
}



回答2:


Dynamic Programming would yield the best runtime for an exact solution. The Subset Sum Problem page on Wikipedia has some pseudo-code for the algorithm. Essentially you order all the numbers and add up all the possible sequences in order such that you minimize the number of additions. The runtime is pseudo-polynomial.

For a polynomial algorithm you could use an Approximation Algorithm. Pseudo-code is also available at the Subset Sum Problem page.

Of the two algorithms I would choose the dynamic programming one since it is straight-forward and has a good runtime with most data sets.

However if the integers are all non-negative and fit with the description on the Wikipedia page then you could actually do this in polynomial time with the approximation algorithm.



来源:https://stackoverflow.com/questions/595707/sum-array-values-with-sum-equals-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!