2007/12/06(Thu) 17:53:11 編集(投稿者)
再帰パターンの実装例。見づらい!
多重Listにしなければもう少し判りやすかっただろうけど、汎用性も希望にあわせてみました。
private void button1_Click(object sender, EventArgs e)
{
List<string> t = new List<string>(new string[]{"あ", "い", "う", "え"});
List<List<string>> r = Combinatorial(t, Int32.MaxValue);
foreach (List<string> v in r)
{
string ss = "";
foreach (string s in v)
{
ss += s;
}
Debug.Print(ss);
}
}
private List<List<string>> Combinatorial(IList<string> src, int nCount)
{
List<List<string>> resultCombi = new List<List<string>>();
if (nCount > 0)
{
if (nCount > 1)
{
if (nCount > src.Count)
{
nCount = src.Count;
}
List<List<string>> parentCombi = Combinatorial(src, nCount - 1);
resultCombi.AddRange(parentCombi);
foreach (List<string> oneOfPattern in parentCombi)
{
List<string> clonePattern = new List<string>(oneOfPattern);
clonePattern.Add(src[nCount - 1]);
resultCombi.Add(clonePattern);
}
}
resultCombi.Add(new List<string>(new string[] { src[nCount - 1] }));
}
return resultCombi;
}