我在尝试更新嵌套 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);
}
}
}
编辑:解决方案需要能够在运行时进行调整,以便用户可以选择需要多少级别。
最佳答案
这是一个递归解决方案(使用 functional programming 样式):
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;
}
示例使用:
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
... */
针对OP的具体场景(添加数组到collection
):
var sequences = GetCombinations(new [] { 10, 20, 10 });
collection.AddRange(sequences.Select(s => s.ToArray()));
关于c# - 递归代替多个嵌套的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914299/