具有递归的重复算法的排列 [英] permutations with repeats algorithm with recursion

查看:61
本文介绍了具有递归的重复算法的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用一个函数而不是必须使用多个函数来让它工作时遇到了一些麻烦.

I'm having some trouble getting this to work using one function, instead of having to use many.

如果我想获得像 2^3 这样的重复排列.重复排列

If I want to get permutations with repeats like 2^3. permutations with repeats

获得:

000
001
101
011
100
101
110
111

我可以有这个功能:

   static void Main(string[] args)
    {
        three_permutations(2);
        Console.ReadLine();
    }


    static void three_permutations(int y)
    {

        for (int aa = 0; aa < y; aa++)
        {
            for (int bb = 0; bb < y; bb++)
            {
                for (int cc = 0; cc < y; cc++)
                {
                    Console.Write((aa));
                    Console.Write((bb));
                    Console.Write((cc));
                    Console.WriteLine();
                }
            }
        }

    }

但是然后做 4(比如 2^4),我能想到的唯一方法是:

But then to do 4 (like 2^4), the only way I can think is this:

  static void four_permutations(int y)
    {
            for (int aa = 0; aa < y; aa++)
            {
                for (int bb = 0; bb < y; bb++)
                {
                    for (int cc = 0; cc < y; cc++)
                    {
                        for (int dd = 0; dd < y; dd++)
                        {
                            Console.Write((aa));
                            Console.Write((bb));
                            Console.Write((cc));
                            Console.Write((dd));
                            Console.WriteLine();
                        }
                    }
                }
            }
     }

但我确定使用递归有更好的方法我只是不知道该怎么做.我很感激任何帮助.谢谢.

but I'm sure there's a better way using recursion I'm just not sure how to do it. I appreciate any help. Thanks.

推荐答案

void permutations(string text, int numberOfDigits, int numberOfChars)
{
    if (numberOfDigits > 0)
        for (int j = 0; j < numberOfChars; j++)
            permutations(text + j.ToString(), numberOfDigits - 1, numberOfChars);
    else textBox1.Text += text + "\r\n";
}

并调用:

permutations("", 3, 2);

这篇关于具有递归的重复算法的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆