算法找出哪些号码从大小为n总和到另一个号码清单 [英] Algorithm to find which numbers from a list of size n sum to another number

查看:125
本文介绍了算法找出哪些号码从大小为n总和到另一个号码清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个十进制数(姑且称之为目标)等十进制数组成的数组(我们称之为数组的元素),我需要找到所有的组合从元素数字该笔款项为目标。

我有一个preference在C#中的溶液(.NET 2.0),但可能的最佳算法赢不论。

您的方法签名可能看起来是这样的:

 公共十进制[] []解决(十进制的目标,小数[]元)
 

解决方案

有趣的答案。谢谢你的指向维基百科 - 而有趣 - 它们实际上并不解决问题,说,我一直在寻找精确匹配 - 比传统的装箱/背包问题会计/书blancing问题。

我一直在下面的堆栈溢出有兴趣的开发,并想知道它是多么有用。这个问题就来了,在工作,我不知道堆栈溢出是否可以提供现成的答案(或一个更好的答案)速度比我可以写我自己。也感谢您的意见建议这个被标记的家庭作业 - 我想这是相当准确鉴于上述情况

对于那些谁感兴趣的话,这里是我的解决方案,它使用递归(当然)我也改变了我对方法签名和去了名单>而不是十进制[] []的返回类型:

 公共类求解{

    私人名单,其中,名单,其中,小数>> mResults;

    公开名单<列表<十进制>>解决(十进制的目标,小数[]元){

        mResults =新的名单,其中,名单,其中,小数>>();
        RecursiveSolve(目标,0.0米,
            新的List<十进制>(),新的名单,其中,小数>(元素),0);
        返回mResults;
    }

    私人无效RecursiveSolve(十进制的目标,小数currentSum,
        名单<十进制>包括,列表与LT;十进制> notIncluded,诠释了startIndex){

        对于(INT指数=在startIndex;指数< notIncluded.Count;指数++){

            十进制nextValue = notIncluded [指数]
            如果(currentSum + nextValue ==目标){
                名单<十进制> newResult =新的名单,其中,小数>(含税);
                newResult.Add(nextValue);
                mResults.Add(newResult);
            }
            否则,如果(currentSum + nextValue<目标){
                名单<十进制> nextIncluded =新的名单,其中,小数>(含税);
                nextIncluded.Add(nextValue);
                名单<十进制> nextNotIncluded =新的名单,其中,小数>(notIncluded);
                nextNotIncluded.Remove(nextValue);
                RecursiveSolve(目标,currentSum + nextValue,
                    nextIncluded,nextNotIncluded,在startIndex ++);
            }
        }
    }
}
 

如果你想要一个应用程序来测试这个工作,试试这个控制台应用程序code:

 类节目{
    静态无效的主要(字串[] args){

        字符串输入;
        十进制的目标;
        十进制元;

        做 {
            Console.WriteLine(请输入目标:);
            输入=到Console.ReadLine();
        }
        而(decimal.TryParse(输入,输出的目标)!);

        Console.WriteLine(请输入内容(用空格隔开));
        输入=到Console.ReadLine();
        字符串[] elementsText = input.Split('');
        名单<十进制> elementsList =新的名单,其中,小数>();
        的foreach(字符串elementText在elementsText){
            如果(decimal.TryParse(elementText,出元素)){
                elementsList.Add(元);
            }
        }

        求解求解器=新解算器();
        名单<列表<十进制>>结果= solver.Solve(目标,elementsList.ToArray());
        的foreach(列表<十进制>导致的结果){
            的foreach(在结果十进制值){
                Console.Write({0} \ t的,价值);
            }
            Console.WriteLine();
        }


        到Console.ReadLine();
    }
}
 

我希望这可以帮助其他人更快地得到他们的答复(无论是家庭作业或其他方式)。

干杯......

I have a decimal number (let's call it goal) and an array of other decimal numbers (let's call the array elements) and I need to find all the combinations of numbers from elements which sum to goal.

I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.

Your method signature might look something like:

public decimal[][] Solve(decimal goal, decimal[] elements)

解决方案

Interesting answers. Thank you for the pointers to wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting / book blancing problem than a traditional bin-packing / knapsack problem.

I have been following the development of stack overflow with interest and wondered how useful it would be. This problem came up at work and I wondered whether stack overflow could provide a ready made answer (or a better answer) quicker than I could write it myself. Thanks also for the comments suggesting this be tagged homework - I guess that is reasonably accurate in light of the above.

For those who are interested, here is my solution which uses recursion (naturally) I also changed my mind about the method signature and went for List> rather than decimal[][] as the return type:

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) {

        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);
                mResults.Add(newResult);
            }
            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++);
            }
        }
    }
}

If you want an app to test this works, try this console app code:

class Program {
    static void Main(string[] args) {

        string input;
        decimal goal;
        decimal element;

        do {
            Console.WriteLine("Please enter the goal:");
            input = Console.ReadLine();
        }
        while (!decimal.TryParse(input, out goal));

        Console.WriteLine("Please enter the elements (separated by spaces)");
        input = Console.ReadLine();
        string[] elementsText = input.Split(' ');
        List<decimal> elementsList = new List<decimal>();
        foreach (string elementText in elementsText) {
            if (decimal.TryParse(elementText, out element)) {
                elementsList.Add(element);
            }
        }

        Solver solver = new Solver();
        List<List<decimal>> results = solver.Solve(goal, elementsList.ToArray());
        foreach(List<decimal> result in results) {
            foreach (decimal value in result) {
                Console.Write("{0}\t", value);
            }
            Console.WriteLine();
        }


        Console.ReadLine();
    }
}

I hope this helps someone else get their answer more quickly (whether for homework or otherwise).

Cheers...

这篇关于算法找出哪些号码从大小为n总和到另一个号码清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆