首页 > 代码库 > 使用C#.NET列举组合数前N项和

使用C#.NET列举组合数前N项和

列举如下列所示的组合数前N项和,代码如下(递归方法里注意去重):

技术分享

 1     static void Main(string[] args)
 2     {
 3         List<string> list = GetSumOfPermutation("abcde", 5).ToList();
 4         File.AppendAllLines(@"C:\Sample.txt", list,Encoding.UTF8);
 5     }
 6 
 7     static IEnumerable<string> GetSumOfPermutation(string source, int maxCount)
 8     {
 9         string temp = string.Empty;
10         if (maxCount > 0)
11         {
12             maxCount = maxCount - 1;
13             for (int i = 0; i < source.Length; i++)
14             {
15                 foreach (var cur in GetSumOfPermutation(source, maxCount))
16                 {
17                     if (cur.Contains(source[i]))
18                         continue;
19                     temp = source[i] + cur;
20                     //Console.WriteLine(temp);
21                     yield return temp;
22                 }
23                 temp = source[i].ToString();
24                 //Console.WriteLine(temp);
25                 yield return temp;
26             }
27         }
28     }

使用C#.NET列举组合数前N项和