如何将嵌套的 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("");

   }



}


墨色风雨
浏览 261回答 1
1回答

慕容3067478

我认为第一步是makeDesign1()正确地重新定义。我们想为我们的绘图传递一个尺寸。我们还想稍微改变边界,让大小为 1 的时候画一颗星,而不是像原来的那样:public static void makeDesign(int n)&nbsp;{&nbsp; &nbsp; for (int i = 0; i < n; i++) // For loop is the one creating the rows&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for (int x = n; x > i; x--) // Nested loop is the one creating the columns&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}下一步是让两个循环都倒计时到 1,以在时机成熟时简化递归:public static void makeDesign(int n)&nbsp;{&nbsp; &nbsp; for (int i = n; i > 0; i--) // For loop is the one creating the rows&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for (int x = i; x > 0; x--) // Nested loop is the one creating the columns&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}现在我们可以简单地将每个循环转换成它自己的递归函数,一个调用另一个:public static void makeDesign(int n)&nbsp;{&nbsp; &nbsp; if (n > 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; makeDesignRow(n);&nbsp; &nbsp; &nbsp; &nbsp; makeDesign(n - 1);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}public static void makeDesignRow(int x){&nbsp; &nbsp; if (x > 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; makeDesignRow(x - 1);&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}输出传递makeDesign()一个 10 的参数,我们得到:> java Main*******************************************************>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java