A A1
B B1
C C1 C2
D D1
E
选2
A B
A B1
A C
A C1
A C2
A D
A D1
A E
A1 B
A1 B1
A1 C
A1 C1
A1 C2
A1 D
A1 D1
A1 E
B C
B C1
B C2
B D
B D1
选3
A B C
A B C1
A B C2
A B D
A B D1
A B E
A B1 C
A B1 C1
A B1 C2
A B1 D
A B1 D1
A B1 E
A C D
A C D1
A C E
A C1 D
A C1 D1
A C1 E
A C2 D
A C2 D1
A C2 E
选4
元素个数不定 求这样的 解决方法
using System; using System.Collections.Generic; using System.Text; namespace Combination { class Program { static void Main(string[] args) { string[] Sample = new string[] { "0", "1", "2", "3", "4", "5","6","7","8","9","a","b","c","d","e","f","g" }; List<string> SampleList = new List<string>(); SampleList.AddRange(Sample); List<string> result = getCombination(SampleList, 3); Console.Read(); }
//从n个字符串中取m个字符的所有组合(无放回抽样) static List<string> getCombination(List<string> SampleList, int m) { if (m == 1) { return SampleList; } List<string> result = new List<string>(); if (SampleList.Count == m) { StringBuilder temp_sb = new StringBuilder(); foreach (string s in SampleList) { temp_sb.Append(s); } result.Add(temp_sb.ToString()); Console.WriteLine(temp_sb.ToString()); return result; } string temp_firstelement = SampleList[0]; SampleList.RemoveAt(0); List<string> temp_samplist1 = new List<string>(); temp_samplist1.AddRange(SampleList); List<string> temp_list1 = getCombination(temp_samplist1, m - 1); foreach (string s in temp_list1) { result.Add(temp_firstelement + s); Console.WriteLine(temp_firstelement + s); } List<string> temp_samplist2 = new List<string>(); temp_samplist2.AddRange(SampleList); List<string> temp_list2 = getCombination(temp_samplist2, m); result.AddRange(temp_list2); return result; } } }
我的直觉告诉我,要用递归
可以一个dfs或状态压缩解决啊。。。