簡體   English   中英

如何將嵌套的 for 循環轉換為遞歸

[英]How To Convert a nested for Loop to Recursive

誰能幫我將這個 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("");
   }


}

我認為第一步是正確重新定義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
**********
*********
********
*******
******
*****
****
***
**
*

> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM