标签:style blog http io color ar for sp strong
用程序实现,找出从n个不同元素中,任取m(m≤n)个元素所有的组合。
需要用到下面的递推公式:
递归实现代码:
1 public static void GetCombination(int source, int num, ref List<string> result, int[] temp = null) 2 { 3 if (temp == null) 4 { 5 temp = new int[num]; 6 } 7 if (source >= num && num >= 1) 8 { 9 temp[num - 1] = source; 10 11 if (num == 1) 12 { 13 result.Add(string.Join(",", temp)); 14 } 15 16 GetCombination(source - 1, num - 1, ref result, temp); 17 18 if (source > num) 19 { 20 GetCombination(source - 1, num, ref result, temp); 21 } 22 23 } 24 }
1 public static void GetCombination2(int source, int num, ref List<string> result, int[] temp = null) 2 { 3 if (temp == null) 4 { 5 temp = new int[num]; 6 } 7 for (int i = source; i >= num; i--) 8 { 9 temp[num - 1] = i; 10 if (num > 1) 11 { 12 GetCombination2(i - 1, num - 1, ref result, temp); 13 } 14 else 15 { 16 result.Add(string.Join(",", temp)); 17 } 18 } 19 }
1 List<string> result = new List<string>(); 2 GetCombination2(5, 3, ref result); 3 foreach (var a in result) 4 { 5 Console.WriteLine(a); 6 }
标签:style blog http io color ar for sp strong
原文地址:http://www.cnblogs.com/zrhai/p/4062700.html