java - 使用阶梯模式为每次调用递归打印两行

标签 java recursion recursive-datastructures

我正在研究数据结构问题。下面列出了作业和我迄今为止所做的事情。

import java.util.Scanner;
import java.util.Random; 
/**
* Recursive methods for fun & profit
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class DSLab2
{
/**
 * Prints 2 lines of text for each recursive call, indicating call number 
     * (a value >= 1, and <= value of numCalls, as illustrated below.  Each
     * level of recursion should be indicated by indenting the input line by
     * r spaces.  For example, if numCalls is 3, the method should print:
 *  call 1
 *   call 2
 *    call 3
 *    back 3
 *   back 2
 *  back 1
 *  @param r the level of method calls
 *  @param numCalls the number of intended levels
 */
public static void stairSteps (int r, int numCalls)
{
    System.out.println("call "+r);
    System.out.println("back "+r);
}

我尝试了以下方法,但它只输出阶梯要求的下半部分。我无法弄清楚如何递归调用该方法,以便在每次调用中打印这两行而不是彼此相邻

public static void stairSteps (int r, int numCalls)

if(numCalls>0)
   {

    for ( int i = 0; i <numCalls ; i++){
    System.out.print(" ");
    }
    System.out.println("back " + r);
    stairSteps(r-1, numCalls-1); 
   }
   else
   return;

有什么建议吗?

最佳答案

public static void stairSteps (int r, int numCalls)
{
    if ( numCalls==0 )
        return ;
    for (int i=0; i<r; i++)
        System.out.print(" ");
    System.out.println("call "+r);

    stairSteps(r+1, numCalls-1) ;

    for (int i=0; i<r; i++)
        System.out.print(" ");
    System.out.println("back "+r);
}

public static void main(String argv[]) {
    stairSteps(1, 4) ;
}



 call 1
  call 2
   call 3
    call 4
    back 4
   back 3
  back 2
 back 1

关于java - 使用阶梯模式为每次调用递归打印两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49268630/

相关文章:

algorithm - CSS和DOM在浏览器中是如何实现的?

带修复的 Haskell AST 注释

java - StackOverflowError 多次发生

java - 查找数组中有多少个不同的值

java - 通过递归从两个列表创建一组列表

java - 了解使用数组中所有可能组合的递归

mysql - 递归表可为空的parent_id

java - 自定义 Java 鼠标监听器?

java - Eclipse OSGI 未满足约束

java多线程(newCachedThreadPool),然后将结果写入一个文件?