一.从指定数组a[n]中取出m位,不重复的所有结果
方法:
//获取的子集合 出现的所有项不会重复,跟子集合的排列顺序没有关系
static void combine(int[] a, int n, int m, int[] b, int M)
{
for (int i = n; i >= m; i--)//注意这里的循环范围
{
b[m - 1] = i - 1;
if (m > 1)
combine(a, i - 1, m - 1, b, M);
else
{
for (int j = M - 1; j >= 0; j--)
{
Console.Write(a[b[j]] + " ");
}
Console.WriteLine();
}
}
}
测试:
//排列组合测试
static void TestTwo()
{
int[] source = { 1, 2, 3, 4 };
int[] result = new int[2];
int sourceCount = source.Length;
int resultCount = result.Length;
combine(source, sourceCount, resultCount, result, resultCount);
}
二、给定数组,将数组中的元素依次排列,得到新的数组。
注意:数组元素个数和新排列数组个数相同,如果数组中有相同元素可能会出现相同的排列结果
方法:
static int n = 0;
static void perm(int[] source, int k, int m)
{
int i;
if (k > m)
{
for (i = 0; i <= m; i++)
{
Console.Write(source[i]);
}
Console.WriteLine();
n++;
}
else
{
for (i = k; i <= m; i++)
{
//索引从0 开始和
swap(ref source[k], ref source[i]);
perm(source, k + 1, m);
swap(ref source[k], ref source[i]);
}
}
}
static void swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
测试:
static void TestThree()
{
int[] source = { 1, 2, 3, 4 };
//排列数组,指定数组索引的开始位置和结束位置
perm(source, 0, source.Length - 1);
Console.WriteLine("总个数:" + n);
}