总和等于X的数组值 [英] Sum array values with sum equals X
本文介绍了总和等于X的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数集合.我需要获得所有值总和等于X的可能性.
I have an integer collection. I need to get all possibilites that sum of values are equal to X.
我需要类似此的东西.
它可以用以下语言编写:delphi,c#,php,RoR,python,cobol,vb,vb.net
It can be written in: delp c#, php, RoR, python, cobol, vb, vb.net
推荐答案
实现此目的的唯一方法是生成所有可能的组合并比较总和值.不过存在优化技术.
The only way to implement this would be generate all possible combinations and compare the sum values. Optimization techniques exists though.
这是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;
}
}
}
这篇关于总和等于X的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文