递归代码到非递归循环

use*_*452 5 java combinations

你好,我希望这个代码非递归我怎么能这样做?

public class test {

    public static void main(String[] args) {
        int[] array = new int[]{0, 1, 2,3};
        int size = 2;
        int[] tmp = new int[size];
        //Arrays.fill(tmp, -1);
        generateCombinations(array, 0, 0, tmp);
    }

    private static void generateCombinations(int[] array, int start, int depth, int[] tmp) {

        if (depth == tmp.length) {
            for (int j = 0; j < depth; j++) {
                System.out.print(array[tmp[j]]);

            } System.out.println();
            return;
        }
        for (int i = start; i < array.length; i++) {
            tmp[depth] = i;
            generateCombinations(array, i + 1, depth + 1, tmp);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

它从特定数字生成所有组合.

Mik*_*ail 0

每个递归都可以重写为迭代,反之亦然。你只需要遵循一个通用的算法:

  1. 确定递归的基本情况。当达到基本情况时,会导致递归结束。每个递归都必须有一个定义的基本情况。此外,每个递归调用必须朝着基本情况前进(否则递归调用将无限执行)。在我们的示例中,基本情况是 n == 0。
  2. 实现一个循环,该循环将迭代直到达到基本情况。
  3. 朝着基本情况取得进展。将新参数发送到循环顶部而不是递归方法。

这背后隐藏着维持不变条件的概念。