排列组合算法(递归)1 - Go语言中文社区

排列组合算法(递归)1


一.从指定数组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);
}



版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u011127019/article/details/51392337
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-05-11 22:42:34
  • 阅读 ( 1767 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢