日期:2014-05-20 浏览次数:20753 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Xml; namespace CSharpTest { class Program { static void Main(string[] args) { IEnumerable<int[]> ii = Compute(1, 3, 5, 3); foreach (int[] i1 in ii) { foreach (int i2 in i1) Console.Write(i2); Console.WriteLine(); } } /// <summary> /// 给出sum、min、max和n四个正整数,请输出所有将sum拆分为n个正整数之和,其中每个正整数k都满足:min <= k <= max。这n个正整数之间可以重复,不过由于加法交换率的作用,1 + 2和2 + 1便算是重复的拆分了。 ///例如,sum = 5,n = 3,min = 1,max = 3,这时候满足条件的拆分方式只有两种: /// 1 + 1 + 3 /// 1 + 2 + 2 /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <param name="sum"></param> /// <param name="count">n</param> /// <returns></returns> public static IEnumerable<int[]> Compute(int min, int max, int sum, int count) { var list = Enumerable.Range(min, max - min + 1); if (count == 1) return from item in list where item == sum select new int[] { item }; return list.SelectMany ( number => Compute(number, max, sum - number, count - 1).Select ( item => item.Concat(new int[] { number }).ToArray() ) ); } } }