C#求组合数和组合的方法
/// <summary>
/// 组合数计算方法,两个参数可以互换,传入负数将会得到<c> 1 </c>;运算发生溢出将返回<c> 0 </c>。
/// </summary>
/// <param name="n">参数</param>
/// <param name="N">参数</param>
/// <returns>组合数。</returns>
internal static ulong C(int n, int N)
{
System.Numerics.BigInteger ret = new System.Numerics.BigInteger(1);
if (n != N && n > 1 && N > 1)
{
int m = N > n ? n : N;
int M = N < n ? n : N;
int c = M - m;
c = c > m ? m : c;
for (int i = M - c + 1; i <= M; i++)
ret *= i;
for (int i = 2; i <= c; i++)
ret /= i;
if (ret > ulong.MaxValue)
ret = 0;
}
else if (n == 1 || N == 1)
{
ret = n > N ? n : N;
}
return (ulong)ret;
}
/// <summary>
/// 组合计算方法,两个参数可以互换。
/// </summary>
/// <param name="n1">参数</param>
/// <param name="n2">参数</param>
/// <returns>组合。</returns>
internal static int[][] CombList(int n1, int n2)
{
int[][] ret = new int[0][];
if (n1 >= n2)
{
ret = Cv(n2, n1);
}
else if (n2 > n1)
{
ret = Cv(n1, n2);
}
return ret;
}
private static int[][] Cv(int n, int N)
{
int[][] ret = new int[0][];
if (n > 0 && N > 0 && N >= n)
{
ulong count = C(n, N);//情况种数
ret = new int[count][];
ret[0] = new int[n];
for (int i = 0; i < n; i++)
{
ret[0][i] = i;
}
for (ulong round = 1; round < count; round++)
{
int[] item = (int[])ret[round - 1].Clone();
MaxValueGrow(item, N);
ret[round] = item;
}
}
return ret;
}
private static void MaxValueGrow(int[] arr, int max)
{
int count = arr.Length;
int M = max - 1;
for (int i = count - 1; i >= 0; i--, M--)
{
if (arr[i] < M)
{
arr[i]++;
M = arr[i];
for (; i < count; i++, M++)
{
arr[i] = M;
}
break;
}
}
}
来源:CSDN
作者:dscn15848078969
链接:https://blog.csdn.net/dscn15848078969/article/details/104415979