打印出数字塔

时间:2019-01-19 18:59:54

标签: java recursion

我正准备为考试做准备,所以我想我会去互联网上找到一些递归示例。现在我发现的任务如下: 您应该编写一个printSequence方法,其中对于n = 3,输出应类似于以下内容
1
12
123
12
1

,且n = 5
1
12
123
1234
12345
1234
123
12
1

现在,我对递归的想法还很陌生,所以很抱歉要求这样的简单任务。但是我无法解决这个问题。我设法在n = 3上打印了这样的内容
123
12
1

但我只是无法掌握上半部分的方法。

public static int printSequence(int n){
    if (n >= 1){
        for (int i = 1; i <= n; i++)
            System.out.print(i);          
        System.out.println();
        return printSequence(n-1);  
    }   
    return 0;
}

可能是我的想法是完全错误的,但是正如我所说,我只是想不出另一种方法。

6 个答案:

答案 0 :(得分:2)

以下代码可能对您有帮助。代码如下。这是不言自明的。但是,如果您觉得它很复杂,我将添加详细的解释。

public static int printSequence(int n) {
    return printSequence(1, n); //start printing upper triangle (1 to n)
}

public static int printSequence(int currentNumber, int lastNumber){
    for (int i = 1; i <= currentNumber; i++)
        System.out.print(i);          
    System.out.println();

    if(currentNumber<lastNumber) //if in upper triangle
        return printSequence(currentNumber+1, lastNumber);

    if(currentNumber>lastNumber) //if in lower triangle
        return printSequence(currentNumber-1, lastNumber);

    if(currentNumber==lastNumber) { //if the end of a triangle is reached

        if(lastNumber==1) {  //if the end of lower triangle is reached, exit the method
            return 0;
        } else {
            return printSequence(lastNumber-1, 1); //if the end of upper triangle is reached, start the lower triangle ( n-1 to 1)
        }

    }
    return 0;
}

答案 1 :(得分:1)

可能有一种更简洁的方法,但是简单的方法是创建另一个函数并在其中传递默认参数:

  1. 您检查当前迭代值i是否大于n,然后退出;
  2. 如果i == n,您只需打印一个字符串(顶峰或金字塔);
  3. 对于其他情况,您需要在所有包含的迭代之前和之后打印行。

例如:

public static int printRecursive(int n, String line, int i) {
     if (i > n) {
        return 0;
    }
    System.out.println(line);
    if (i == n) {
        return 0;
    }
    printRecursive(n, line + " " + (++i), i);
    System.out.println(line);
    return 0;
 }

 public static int printSequence(int n){
    return printRecursive(n, "1", 1);
 }

答案 2 :(得分:1)

这似乎有效。注意:

  • 它不是递归printSequence,而是接受限制(n)并充当包装器,以从1开始调用递归方法。
  • 递归方法接受当前字符串作为参数,因此代码不必每次都从1重新构造字符串,只需附加最后一位。
  • (初始)参数超出范围时进行错误检查以引发异常。
public static void main(String[] args) {
    printSequence(5);  // test value
}

private static void printSequence(int n) {
    if (n < 1 || n > 9) {
        throw new IllegalArgumentException("Argument must be in the range 1 to 9 inclusive.");
    }
    doRecursion(1, "", n);  // call recursive method with initial values
}

private static void doRecursion(Integer counter, String currentString, int limit) {
    String newString = currentString + counter.toString();
    System.out.println(newString);
    if (counter < limit) {
        doRecursion(counter + 1, newString, limit);
        System.out.println(newString);
    }
}

答案 3 :(得分:1)

这正是您想要的:

   //This is the method that will be called from some other class
   public static int printSequence(int n){
       return printSequence(1, n);
   }

   /*We define this method, because the following code snippet
    is used multiple times in the method 'printSequence(int, int)'
    This method will simply print the numbers 1 - length*/
   private static void printLooper (int length){
        for(int i=1; i<=length; i++)
            System.out.print(i);
        System.out.print("\n");
    }

    /*This method has the logic. We give it 2 integers as parameters:
     int start and int end. I think the names of the parameters are self-explanatory*/
    private static int printSequence(int start, int end){
        /*This is the TERMINATING condition, so it is placed first.
         This part is really important. Always be aware of what type of recursion
         you are using. More on this later..*/
        if ( end == 1 ) {
            printLooper(end);
            return 0;
        }

        //OK. So, if start is less than end, then print 1 - start
        if (start < end){
            printLooper(start);
            //then return method recursively, with start INCREMENTED by one
            return printSequence(start+1, end);
        }

        /*Now, if start is equal to end, print number 1 - start, but this time,
        return the method recursively with end DECREMENTED by one*/
        else if (start == end){
            printLooper(start);
            return printSequence(start, end-1);
        }

        /*Now if start is larger than end, then that means that we need to start
         printing the lower part of the 'number tree'. So, call printLooper()
         to print 1 - end.*/
        else if (start > end){
            printLooper(end);
            return printSequence(start, end-1);
        }
        return 0;
    }
  

关于递归的类型以及为什么知道要编写的函数类型很重要,请查看this awesome tutorial

答案 4 :(得分:1)

我认为此解决方案可能有效,但是它使用了2个功能。每个函数都具有递归:

public static void printSequence(int n){
    printSequenceHelp1(1, n - 1);
    for (int i = 1; i <= n; i++)
        System.out.print(i);          
    System.out.println();
    printSequenceHelp2(n - 1);  
}

public static void printSequenceHelp1(int k, int n){
    if (k <= n){
        for (int i = 1; i <= k; i++)
            System.out.print(i);          
        System.out.println();
        printSequenceHelp1(k + 1, n);
    }   
}

public static void printSequenceHelp2(int n){
    if (n >= 1){
        for (int i = 1; i <= n; i++)
            System.out.print(i);          
        System.out.println();
        printSequenceHelp2(n - 1);  
    }   
}

我敢肯定,只有一个功能有一个更优雅的解决方案。如果可以找到它,我会在这里发布。

答案 5 :(得分:1)

递归解决方案

public static int printSequence(int n,int count){
    if(count == 2*n){
        return 0;
    }
    else{
        if(count<=n){
            int i=1;
            while(i<=count)
            {
                System.out.print(i);
                i++;
            }
            System.out.println();
            return printSequence(n,count+1);
        }
        else{
            int i=1;
            while(i<=n-(count-n)) 
            {
                System.out.print(i);
                i++;
            }
            System.out.println();
            return printSequence(n,count+1);
        }
    }
}

printSequence(n,1);