C#算法 - 列数的所有排列 [英] C# algorithm - listing all permutations of number

查看:95
本文介绍了C#算法 - 列数的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是形式的跟进一个问题我在前面贴(<一href="http://stackoverflow.com/questions/1940980/c-algorithm-find-least-number-of-objects-necessary">http://stackoverflow.com/questions/1940980/c-algorithm-find-least-number-of-objects-necessary),但有点不同的。

This is sort of a follow up to a question I posted earlier (http://stackoverflow.com/questions/1940980/c-algorithm-find-least-number-of-objects-necessary), but a bit different.

由于我有以下的code:

Given I have the following code:

var max = 80;
var list = new[]{10,20,30,40,50, 60);

我要生成一个包含所有可能的组合,我可以用这些数字在列表中获取到最大号的数组。

I want to generate a array containing all the possible combinations I can use those numbers in the list to get to that max number.

该数组将包含,{40,40},{50,30},{40,30,10}等等...

The array would contain, {40, 40}, {50, 30}, {40,30, 10} etc...

推荐答案

您会想遍历所有的数字按降序排列。然后点击递归序列中添加的每个下一降数。每次和匹配,注意组合,蹦出来,然后继续前进。当您的暂定金额需要你在最大变量,弹出的功能在堆栈中的下一个函数。如果max仍然还没有达到,依次添加下一个数字向下序列中。通过这种方式,你将永远覆盖可能的顺序,没有重复的(除非有在给定的重复,你会在这种情况下要重复的)。这将是没有太多code其实。

You'll want to iterate over all the numbers in descending order. Then recursively add each next descending number in the sequence. Each time the sum matches, note that combo, pop out, and move on. When your tentative sum takes you over the max variable, pop out of the function to the next function in the stack. If the max still hasn't been reached, successively add the next number down in the sequence. In this way you will cover ever possible sequence, with no duplicates (unless there are duplicates in the given set, in which case you would want that duplicate). It will be not too much code actually.

这篇关于C#算法 - 列数的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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