使用C#.NET列舉組合數前N項和

列舉以下列所示的組合數前N項和,代碼以下(遞歸方法裏注意去重):
spa

 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     }
相關文章
相關標籤/搜索