1

与此类似:有没有办法在 Java 中执行 n 级嵌套循环?

我想创建一个递归函数,它生成 N 个嵌套循环,其中的索引取决于循环的深度。所以基本上,我想递归地这样做:

// N = 3, so we want three nested loops

for(int i1 = 0; i1 < max; i1++){
    for(int i2 = i1+1; i2 < max; i2++){
        for(int i3 = i2+1; i3 < max; i3++){
            int value1 = getValue(i1);
            int value2 = getValue(i2);
            int value3 = getValue(i3);
            doSomethingWithTheValues( ... );
        }
    }
}

我查看了另一个问题的答案,并尝试修改答案(由 oel.neely),但没有运气。我的猜测是它只需要一个小的修改,但现在,我只是让自己感到困惑!

4

1 回答 1

2

它的 C#,但应该很容易转换为 Java:

class ImmutableStack<T>
{
    public readonly T Head;
    public readonly ImmutableStack<T> Tail;

    public ImmutableStack(T head, ImmutableStack<T> tail)
    {
        this.Head = head;
        this.Tail = tail;
    }

    public static ImmutableStack<T> Cons(T head, ImmutableStack<T> tail)
    {
        return new ImmutableStack<T>(head, tail);
    }

    public static ImmutableStack<T> Reverse(ImmutableStack<T> s)
    {
        ImmutableStack<T> res = null;
        while (s != null)
        {
            res = Cons(s.Head, res);
            s = s.Tail;
        }
        return res;
    }
}

class Program
{
    static void AwesomeRecursion(int toDepth, int start, int max, ImmutableStack<int> indices)
    {
        if (toDepth < 0)
        {
            throw new ArgumentException("toDepth should be >= 0");
        }
        else if (toDepth == 0)
        {
            Console.Write("indices: ");
            indices = ImmutableStack<int>.Reverse(indices);
            while (indices != null)
            {
                Console.Write("{0}, ", indices.Head);
                indices = indices.Tail;
            }
            Console.WriteLine();
        }
        else
        {
            for (int i = start; i < max; i++)
            {
                AwesomeRecursion(toDepth - 1, i + 1, max, ImmutableStack<int>.Cons(i, indices));
            }
        }
    }


    static void Main(string[] args)
    {
        AwesomeRecursion(4, 1, 10, null);
        Console.WriteLine("Done");
        Console.ReadKey(true);
    }
}

我们将索引保存在不可变堆栈上,因为它使回溯比可变堆栈或队列容易得多。

于 2010-02-22T04:48:16.187 回答