输入一个string[]和要求的多少种组合X,
然后枚举出组合
假设:
string[] list=new string[]{"a","b","c","d","e"}
求X=3的组合
就枚举出
abc
abd
abe
acd
...
...
这种组合算法怎么算.
list和X都是传进去的,不是固定为3的.
然后枚举出组合
假设:
string[] list=new string[]{"a","b","c","d","e"}
求X=3的组合
就枚举出
abc
abd
abe
acd
...
...
这种组合算法怎么算.
list和X都是传进去的,不是固定为3的.
http://topic.csdn.net/u/20110610/13/d1924231-0a45-4826-ac2a-7bbcfcb9fc93.html?18794
using System.Collections.Generic;
using System.Linq;namespace ConsoleApplication2
{
class Program
{
public static void Main()
{
string[] list = new string[] { "a", "b", "c", "d", "e", "MM" };
var X = 3;
var cnt = 0;
foreach (var s in 你的组合(list, X))
Console.WriteLine("第{0}个结果:\t{1}", ++cnt, string.Join(string.Empty, s));
Console.ReadKey();
} private static IEnumerable<string[]> 你的组合(string[] list, int X)
{
if (X == 1)
{
foreach (var s in list)
yield return new string[] { s };
}
else if (X > 1)
{
for (var i = 0; i < list.Length; i++)
{
var newList = list.Where((s, p) => p != i).ToArray();
foreach (var sub in 你的组合(newList, X - 1))
for (var j = 0; j < sub.Length; j++)
{
var ret = sub.ToList();
ret.Insert(j, list[i]);
yield return ret.ToArray();
}
}
}
}
}
}