在一组数字中找到总和等于已知数字的组合的有效算法 [英] Efficient algorithm to find a combination, which summation is equal to a known number, in a set of number
问题描述
假设有一组数字
1、2、3、4、5、6、7、8、9 ,10
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
我想找出一组数字中的几种组合,以使其总和等于已知数字,例如18。我们可以找到匹配的5、6、7(5 + 6 + 7 = 18)。
I want to find out several combinations in the set of number such that the summation of it equal to a known number, for example, 18. We can find out that 5, 6, 7 is matched (5+6+7=18).
组合中的数字不能重复,而且集合中的数字可能不连续。
Numbers in a combination cannot be repeated and the number in a set may not be consecutive.
I' ve编写了一个C#程序来做到这一点。该程序是随机选择号码以形成组合并检查组合的总和是否等于已知数字。但是,该程序找到的组合可能会重复进行,从而使进度无效。
I've wrote a C# program to do that. The program is random to pick up number to form a combination and check whether the summation of combination is equal to a known number. However, the combination the program found may be repeated and it makes the progress not effective.
我想知道是否有任何有效的算法可以找到这种组合。
I am wondering whether there is any efficient algorithm to find out such combination.
这是我的代码的一部分。
Here's part of my code.
int Sum = 0;
int c;
List<int> Pick = new List<int>();
List<int> Target = new List<int>() {some numbers}
Target.Sort();
while (!Target.Contains(Sum))
{
if (Sum > Target[Target.Count - 1])
{
Pick.Clear();
Sum = 0;
}
while (true)
{
if (Pick.IndexOf(c = Math0.rand(0, Set.Count - 1)) == -1)
{
Pick.Add(c);
}
//Summation Pick
Sum = 0;
for (int i = 0; i < Pick.Count; i++)
Sum += Set[Pick[i]];
if (Sum >= Target[Target.Count - 1])
break;
}
}
Result.Add(Pick);
推荐答案
您可以使用递归。对于集合中的任何给定数字,找到将其相加的较小数字的组合:
You can use recursion. For any given number in the set, find the combinations of smaller numbers that adds up to the number:
public static IEnumerable<string> GetCombinations(int[] set, int sum, string values) {
for (int i = 0; i < set.Length; i++) {
int left = sum - set[i];
string vals = set[i] + "," + values;
if (left == 0) {
yield return vals;
} else {
int[] possible = set.Take(i).Where(n => n <= sum).ToArray();
if (possible.Length > 0) {
foreach (string s in GetCombinations(possible, left, vals)) {
yield return s;
}
}
}
}
}
用法:
int[] set = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (string s in GetCombinations(set, 18, "")) {
Console.WriteLine(s);
}
输出:
1,2,4,5,6,
3,4,5,6,
1,2,3,5,7,
2,4,5,7,
2,3,6,7,
1,4,6,7,
5,6,7,
1,2,3,4,8,
2,3,5,8,
1,4,5,8,
1,3,6,8,
4,6,8,
1,2,7,8,
3,7,8,
2,3,4,9,
1,3,5,9,
4,5,9,
1,2,6,9,
3,6,9,
2,7,9,
1,8,9,
1,3,4,10,
1,2,5,10,
3,5,10,
2,6,10,
1,7,10,
8,10,
这篇关于在一组数字中找到总和等于已知数字的组合的有效算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!