根据网络的组合算法改写成的泛型组合函数
/// <summary>
/// 获取不同组合/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="el">组合的元素列表</param>
/// <param name="n">个数</param>
/// <returns></returns>
public List<T[]> GetCom<T>(T[] el, int n)
{
string s = "";
int p = 0;
int m = el.Length;
int[] flags = new int[m];
List<T[]> oList = new List<T[]>();
for (int i = 0; i < n; i++)
{
flags[i] = 1;
}
for (int i = n; i < m; i++)
{
flags[i] = 0;
}
p = 0;
T[] ArrT = new T[n];
int Arrindex = 0;
for (int i = 0; i < flags.Length; i++)
{
if (flags[i] == 1)
{
p++;
ArrT[Arrindex] = el[i];
Arrindex++;
}
}
oList.Add(ArrT);
int count = 1;
bool has10 = false; //是否有"10"组合的标志:true-有;false-无
int bound = 0; //第一个"10"组合的索引
int num1 = 0; //"10"组合左边的"1"的个数
int j;
while (true)
{
num1 = 0;
has10 = false;
for (int i = 0; i < m - 1; i++)
{
if (flags[i] == 1 && flags[i + 1] == 0)//找到第一个"10"组合
{
bound = i;
flags[i] = 0;//将该"10"组合变为"01"组合
flags[i + 1] = 1;
for (j = 0; j < num1; j++)//将其左边的所有"1"全部移动到数组的最左端
{
flags[j] = 1;
}
for (j = num1; j < bound; j++)
{
flags[j] = 0;
}
has10 = true;
break;
}
else if (flags[i] == 1)
{
num1++;
}
}
if (has10 == false)//没有"10"组合了,代表组合计算完毕
{
break;
}
else
{
count++;
}
p = 0;
T[] tmp_ArrT = new T[n];
int tmp_Arrindex = 0;
for (int i = 0; i < flags.Length; i++)
{
if (flags[i] == 1)
{
p++;
tmp_ArrT[tmp_Arrindex] = el[i];
tmp_Arrindex++;
}
}
oList.Add(tmp_ArrT);
}
return oList;
}
//------------------调用方式
int[] el={1,2,3,4,5};
List<int[]> oList = GetCom<int>(el, 2);