首页 > 解决方案 > 仅使用递归打印 V 形

问题描述

我正在尝试仅使用递归打印出字母 V 的形状。我在这个网站上看到了一些与我的问题相关的代码,但大多数使用循环而不是递归。

这是我的代码:

  public class Pattern {

    public static void main(String[] args) {
         printPattern(5);
    }
       public static void Pattern(int count, String s) {
        if (count == 0) {
            return;
        }

        System.out.print(s);
        Pattern(count - 1, s);
    }

    public static void upperhalf(int count, int max) {
        if (count == 0) {
            return;
        }

        Pattern(max - count, " ");
        Pattern(count, "* ");

        System.out.println();

        upperhalf(count - 1, max);
    }



    public static void printPattern(int n) {
        upperhalf(n, n);

    }
}

输出:

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

我想要的输出:

  *       *
   *     *
    *   *
     * *
      *

标签: javarecursion

解决方案


解决它的一种方法。用这个替换你的两个连续模式调用:

    Pattern(max - count, " ");
    Pattern(1, "* ");
    Pattern(count - 2, "  ");
    Pattern(1, count > 1 ? "* " : "");        

(即您的第一个 Pattern 调用,然后是单个 * 的显式调用,然后是几个空格(比您的方法少 2 个),然后是最后一个 *)。

您还需要稍微更改退出语句:

public static void Pattern(int count, String s) {
    if (count <= 0) { // <= instead of ==
        return;
    }

推荐阅读