如何获得可以使用给定数字形成的所有可能的n位数字? [英] How to get all possible n-digit numbers that can be formed using given digits?

查看:47
本文介绍了如何获得可以使用给定数字形成的所有可能的n位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编码一个大型应用程序的一部分,而我正面临这个问题.我将通过介绍一个类似的普通场景,从所有细节中提取所有人.

I am coding a part of a big application where I am facing this problem. I will abstract you all from all the details by presenting a similar plain-vanilla scenario.

我得到n(在运行时要形成的数字的位数).

I am given n (the no. of digits of the number to be formed at run-time).

我还得到了一个数字列表,例如{2,4,8,9}.

I am also given a list of numbers say {2,4,8,9}.

我必须形成可以从上述给定长度的列表中形成的所有可能的数字.

I have to form all the possible numbers that can be formed from the above list of the given length.

例如如果n = 3且列表= {4,5,6}

e.g. if n = 3 and list = {4, 5, 6}

那么可能的数字是:

444,
445,
446,
454,
455,
456,
464,
465,
466, 

以此类推...

任何帮助将不胜感激!

致谢

shahensha

shahensha

推荐答案

您可以使用递归. 假设您可以使用的数字在一个数组中.

You can use recursion. Say the numbers you can use are in an array.

C#代码:

static int[] digits = new int[] {4, 5, 6};

static void Rec(int current, int numDigits) {
    if(numDigits==0)
        Console.WriteLine(current);
    else
        foreach(int x in digits)
            Rec(current*10+x, numDigits-1);
}

然后致电:

static void Main(string[] args){
    Rec(0, 3);
}

这篇关于如何获得可以使用给定数字形成的所有可能的n位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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