首页 > 解决方案 > 如何将嵌套的 for 循环转换为递归

问题描述

谁能帮我将这个 for 循环转换为递归方法:到目前为止,我添加了这两种方法,但我仍然想更改第二个循环。先感谢您。

       public void makeDesign1() {
    int x;
    for (int i = 0; i < 5; i++) // For loop is the one creating the rows
    {
        for (x = 4; x > i; x--) // Nested loop is the one creating the columns 
        {
            System.out.print("*");
        }
        System.out.println();
    }
    System.out.println();

}

public static int makeDesign1Recur(int i) {

    if (i == 0) {
        return 0;
    }
    System.out.print("*");
    return (makeDesign1Recur(i-1));
}
// How to convert this second loop recursive?
public static void makeDesignRow(int i){
   for ( int x = i; x>=0; x--){
       makeDesign1Recur(x);
       System.out.println("");
   }


}

标签: javaloopsfor-looprecursion

解决方案


我认为第一步是makeDesign1()正确地重新定义。我们想为我们的绘图传递一个尺寸。我们还想稍微改变边界,让大小为 1 的时候画一颗星,而不是像原来的那样:

public static void makeDesign(int n) 
{
    for (int i = 0; i < n; i++) // For loop is the one creating the rows
    {
        for (int x = n; x > i; x--) // Nested loop is the one creating the columns 
        {
            System.out.print("*");
        }

        System.out.println();
    }

    System.out.println();
}

下一步是让两个循环都倒计时到 1,以在时机成熟时简化递归:

public static void makeDesign(int n) 
{
    for (int i = n; i > 0; i--) // For loop is the one creating the rows
    {
        for (int x = i; x > 0; x--) // Nested loop is the one creating the columns 
        {
            System.out.print("*");
        }

        System.out.println();
    }

    System.out.println();
}

现在我们可以简单地将每个循环转换成它自己的递归函数,一个调用另一个:

public static void makeDesign(int n) 
{
    if (n > 0)
    {
        makeDesignRow(n);
        makeDesign(n - 1);
    }
    else
    {
        System.out.println();
    }
}

public static void makeDesignRow(int x)
{
    if (x > 0)
    {
        System.out.print("*");
        makeDesignRow(x - 1);
    }
    else
    {
        System.out.println();
    }
}

输出

传递makeDesign()一个 10 的参数,我们得到:

> java Main
**********
*********
********
*******
******
*****
****
***
**
*

> 

推荐阅读