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

我有一些问题尝试更新嵌套的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); } } } 

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

好的,试试吧

 static void AddToCollectionRecursive( List collection, params int[] counts) { AddTo(collection, new List(), counts, counts.Length - 1); } static void AddTo( List collection, IEnumerable value, IEnumerable 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); } } } 

用法就像这个AddToCollectionRecursive(collection, 10, 20, 10);

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

 public static IEnumerable> GetCombinations(IEnumerable limits) { if (limits.Any() == false) { // Base case. yield return Enumerable.Empty(); } else { int first = limits.First(); IEnumerable remaining = limits.Skip(1); IEnumerable> tails = GetCombinations(remaining); for (int i = 0; i < first; ++i) foreach (IEnumerable tail in tails) yield return Yield(i).Concat(tail); } } // Per http://stackoverflow.com/q/1577822 public static IEnumerable Yield(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())); 

这样的东西会起作用:

 public void CreateIndexes(int a, int b, int c, Collection collection) { if(c == 10) {b++; c = 0;} if(b == 20) {a++; b = 0;} if(a == 10) return; int[] indexes = new int[3]{a,b,c} collection.add(indexes); c++; CreateIndexes(a, b, c, collection); } 

在我的头顶,即未经测试,这样的事情可能会起作用:

  List collection = new List(); private void AddValues(int a, int b, int c) { collection.Add(new[] { a, b, c }); if (c < 10) { c++; AddValues(a, b, c); } if (b < 20) { b++; c = 0; AddValues(a, b, c); } if (a < 10) { a++; b = 0; c = 0; AddValues(a, b, c); } } 

通过调用启动它:

 AddValues(0, 0, 0); 

好吧,我认为如果你使用递归解决这个问题,它会消耗更多的回忆和资源!

但有我的建议:

 private void FunctionName(int a, int b, int c, List list) { if (a<10) { if (b<20) { if (c<10) { list.Add(new[] { a, b, c }); c++; FunctionName(a,b,c,list); } else { c=0; b++; FunctionName(a,b,c,list); } } else { b=0; a++; FunctionName(a,b,c,list); } } } 

你这样调用:FunctionName(0,0,0,list)。

希望它有效! ^^