日期:2014-05-18  浏览次数:20725 次

怎么根据参数决定循环的层数
比如,我要实现这样的功能
C# code

private void fun(int[] arr)
{
    int n = arr.Length;
    int[] i = new int[n];
    for(i[0]=0; i[0]<arr[0]; i[0]++)
    {
        for(i[1]=0; i[1]<arr[1]; i[1]++)
        {
            ...// 这里该怎么写?

                for(i[n-1]=0; i[n-1]<arr[n-1]; i[n-1]++)
                {
                    fun2(i);    //这里的参数是i
                }
        }
    }
}


中间那个循环该怎么实现呢?

------解决方案--------------------
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[] { 3, 2, 4 };
            fun(arr);
        }

        static private void fun(int[] arr)
        {
            fun1(arr, null, 0);
        }

        static private void fun1(int[] arr, int[] a2, int i)
        {
            if (a2 == null) a2 = new int[arr.Length];
            if (i < arr.Length)
            {
                for (int j = 0; j < arr[i]; ++j)
                {
                    a2[i] = j;
                    fun1(arr, a2,i + 1);
                }
            }
            else
            {
                func2(a2);
            }
        }

        static private void func2(int[] a2)
        {
            Console.WriteLine(string.Format("{0}   {1}   {2}", a2[0], a2[1], a2[2]));
        }
    }
}



运行结果:
0   0   0
0   0   1
0   0   2
0   0   3
0   1   0
0   1   1
0   1   2
0   1   3
1   0   0
1   0   1
1   0   2
1   0   3
1   1   0
1   1   1
1   1   2
1   1   3
2   0   0
2   0   1
2   0   2
2   0   3
2   1   0
2   1   1
2   1   2
2   1   3
请按任意键继续. . .