【问题标题】:Print pyramid using recursion only仅使用递归打印金字塔
【发布时间】:2016-11-26 00:37:19
【问题描述】:

我设法用这样的循环打印了一个金字塔:

void printtree() {
  for (int i=0; i<row; i++){
    for (int j=0; j<row-i-1; j++)
      System.out.print(" ");
    for (int k=row; k>row-i-1; k--)
      System.out.print("* ");
    System.out.println();
  }
}

输出如下:

        * 
       * * 
      * * * 
     * * * * 
    * * * * * 
   * * * * * * 
  * * * * * * * 
 * * * * * * * * 
* * * * * * * * * 

我想只使用递归,我应该如何构造函数?我关心的是嵌套循环,我只能解释单个内部或外部循环。我知道它被解释为 (row-1) 空格,后跟每行上的“*”行 #,然后更改为新行。这里的基本情况是什么?

【问题讨论】:

  • 想象一下:为了打印偏移量为 K 个空格的最后 N 颗星,您应该首先打印偏移量为 K+1 个空格的 N-1 颗星。
  • 你研究过递归吗?如果是这样,您是否尝试过自己实现此功能?当然,如果你不做任何研究,你会很难过。如果您已经尝试过,但无法让您的实现工作,请发布您的尝试

标签: java recursion


【解决方案1】:

因为您希望解决方案仅使用递归。我假设您不希望程序中有任何循环。如果您想将程序快速转换为递归方法,请查看每个 for 循环并思考如何转换它。

你可以转换

 for (int j=0; j<row-i-1; j++)
      System.out.print(" ");

发挥作用

static void printSpace(int j, int i) {
        if (j < row - i - 1) {
            System.out.print(" ");
            printSpace(j + 1, i);
        }
    }

请注意,上面的递归函数与您的 for 循环相同。它需要您在 for 循环中使用的相同参数。现在这个技巧你可以应用到 f​​or 循环中,它也可以打印星号。

static void printStar(int k, int i) {
        if (k > row - i - 1) {
            System.out.print("* ");
            printStar(k - 1, i);
        }
    }

类似的技巧可以应用于外部for循环,你可以转换代码。

完整代码

static int row = 5;

    static void printtree() {
        printPyramid(0);
    }

    static void printPyramid(int i) {
        printSpace(0, i);
        printStar(row, i);
        System.out.println();

        if (++i < row)
            printPyramid(i);
    }

    static void printSpace(int j, int i) {
        if (j < row - i - 1) {
            System.out.print(" ");
            printSpace(j + 1, i);
        }
    }

    static void printStar(int k, int i) {
        if (k > row - i - 1) {
            System.out.print("* ");
            printStar(k - 1, i);
        }
    } 

【讨论】:

    【解决方案2】:
    static void recursion(int row, int k, int j)
    {
    if(row>10)
    {
        return;
    }
    else
    {
        if(k==row)
        {
        System.out.println();
        recursion(++row, 0,0);
        }
        else if(10-j>row)
        {
        System.out.print(" ");
        ++j;
        recursion(row, k, j);
        }
        else
        {
    
        System.out.print("* ");
        recursion(row, ++k, j);
        }   
    }
    }
    

    调用方法

    recursion(0,0,0);
    

    【讨论】:

    • 投反对票,因为这里没有解释;这只是一个代码转储。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多