C#递归循环

时间:2014-10-08 10:18:35

标签: java c# recursion

我有这些数据

string [] letters = {"a","b","c"};

我想要一个像generateString(1)这样的函数 如果value为1,则输出为:

a
b
c

如果是generateString(3),则输出为

a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
aab
aac
aba
abb
abc
aca and so on...

我可以这样做,

foreach(var a in data){
 foreach(var b in data){
  foreach(var c in data){
    Console.WriteLine(a + b + c);
  }
 }
}

它只能产生最多3个,如果我想让它4,那么我添加另一个foreach,这是我认为不是一个更好的主意。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

它看起来像这样

List<List<String>> foo(int i){
    if(i==1){
        return new List<List<String>>(new List<String>("a", "b", "c"));
    } else{
        var result = new List<List<String>>();
        foreach(List<String> list in foo(i-1)){
            foreach(String elem in new String[]{"a", "b", "c"}){
               var tmp = new List<String>(list);
               tmp.Add(elem);
               result.Add(tmp);
            }
        }
        return result;
    }
}

我不确定语法和列表构造函数,但总的来说是显示

答案 1 :(得分:0)

static string[] generateString(string[] letters, int len)
{
    if (len < 0) throw new ArgumentOutOfRangeException("length can't be less than zero.");
    switch (len)
    {
        case 0: return new string[0];
        case 1: return letters;
        default:
            // all possible combinations which are shorter than required 
            // recursion is used here
            var shorter_x = generateString(letters, len - 1).ToArray();

            // all combinations which have length = len - 1
            var shorter_1 = shorter_x.Where(line => line.Length == len - 1).ToArray();

            // resulting array
            return shorter_x.Union(letters.SelectMany(letter => shorter_1.Select(shorter => letter + shorter))).ToArray();
    }
}

UPD:将数据表示为

char[] letters = { 'a', 'b', 'c' }

会更加一致。在这种情况下,函数看起来像

static string[] generateString(char[] letters, int len)
{
    if (len < 0) throw new ArgumentOutOfRangeException("length can't be less than zero.");
    switch (len)
    {
        case 0: return new string[0];
        case 1: return letters.Select(char.ToString).ToArray();
        default:
            ......