我有一个整数集合.我需要得到值总和等于X的所有可能性.
我需要像这样.
它可以写成:delphi,c#,php,RoR,python,cobol,vb,vb.net
这是一个子集和问题.它是NP-Complete.
实现这一点的唯一方法是生成所有可能的组合并比较总和值.但是存在优化技术.
这是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 IEnumerablePermute(int[] data) { return Permute(data, 0); } static IEnumerable 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; } } }