递归代替多个嵌套for循环?

Han*_*del 4 c# recursion c#-4.0

我有一些问题,试图更新嵌套的for循环,而不是使用递归.使用递归时,是否可以从早期的for循环访问a,b和c变量?下面是我试图转换为递归调用的简单示例.

for(int a= 0; a < 10; a++)
{
    for(int b = 0; b < 20; b++)
    {
        for(int c = 0; c < 10; c++)
        {
            int[] indexes = new int[3]{a,b,c}
            collection.add(indexes);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:解决方案需要能够在运行时进行调整,以便用户可以选择需要多少级别.

Dou*_*las 8

这是一个递归解决方案(使用函数式编程风格):

public static IEnumerable<IEnumerable<int>> GetCombinations(IEnumerable<int> limits)
{
    if (limits.Any() == false)
    {
        // Base case.
        yield return Enumerable.Empty<int>();
    }
    else
    {
        int first = limits.First();
        IEnumerable<int> remaining = limits.Skip(1);
        IEnumerable<IEnumerable<int>> tails = GetCombinations(remaining);

        for (int i = 0; i < first; ++i)
            foreach (IEnumerable<int> tail in tails)
                yield return Yield(i).Concat(tail);
    }
}

// Per http://stackoverflow.com/q/1577822
public static IEnumerable<T> Yield<T>(T item)
{
    yield return item;
}
Run Code Online (Sandbox Code Playgroud)

样品用途:

var sequences = GetCombinations(new [] { 5, 3, 2, 4 /* ... */ });
foreach (var sequence in sequences)
    Console.WriteLine(string.Join(", ", sequence));

/* Output:
0, 0, 0, 0
0, 0, 0, 1
0, 0, 0, 2
0, 0, 0, 3
0, 0, 1, 0
0, 0, 1, 1
0, 0, 1, 2
0, 0, 1, 3
0, 1, 0, 0
0, 1, 0, 1
0, 1, 0, 2
... */
Run Code Online (Sandbox Code Playgroud)

对于OP的特定场景(添加数组collection):

var sequences = GetCombinations(new [] { 10, 20, 10 });
collection.AddRange(sequences.Select(s => s.ToArray()));
Run Code Online (Sandbox Code Playgroud)


Ale*_*ria 5

好的,试试这个

static void AddToCollectionRecursive(
    List<int[]> collection,
    params int[] counts)
{
    AddTo(collection, new List<int>(), counts, counts.Length - 1);
}

static void AddTo(
    List<int[]> collection,
    IEnumerable<int> value,
    IEnumerable<int> counts,
    int left)
{
    for (var i = 0; i < counts.First(); i++)
    {
        var list = value.ToList();

        list.Add(i);

        if (left == 0)
        {
            collection.Add(list.ToArray());
        }
        else
        {
            AddTo(collection, list, counts.Skip(1), left - 1);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法是这样的AddToCollectionRecursive(collection, 10, 20, 10);