【问题标题】:Recursion depth - tabs & dents in Java递归深度 - Java 中的制表符和凹痕
【发布时间】:2015-02-13 20:12:44
【问题描述】:

我想格式化我的 Java 程序输出,以便我可以看到递归的“深度”。怎么做? 不要迷失在我的递归树中,这一点非常重要。

示例输出(从 0 开始计算第 n 个数字的简单递归函数):

This is the first recursive call. Input value: 3.
    This is the second recursive call. Input value: 2.
        This is the 3rd recursive call. Input value: 1.
        Output value : 1.
    This is again the second recursive call. Input value: 2.
    Output value : 1 + 1.
This is again the first recursive call. Input value: 3.
Output value : 1 + 1 + 1.

【问题讨论】:

  • 最简单(如果不是最干净)的方法是简单地将int depth 作为参数添加到您的递归方法中,并在您的方法调用自身时增加它。然后,您可以使用它来确定要在输出字符串上添加多少个选项卡。

标签: java recursion tabs formatting


【解决方案1】:

您可以使用表示您的深度的变量(如level)。它从 1 开始,并在每次递归调用时递增。

public static void main(String[] args) {
    function(3, 1);
}

public static String function(int input, int level) {
    String tab = "";
    for (int i = 0; i < level - 1; i++) {
        tab += "\t";
    }
    System.out.println(tab + "This is the " + level + " recursive call. Input value: " + input);
    if (input == 1) {
        System.out.println(tab + "Output value: 1");
        return "1";
    }
    String output = function(input - 1, level + 1);
    System.out.println(tab + "This is again the " + level + " recursive call. Input value: " + input);
    System.out.println(tab + "Output value: " + output + " + 1");
    return output + " + 1";
}

【讨论】:

  • 您的解决方案似乎很清楚,没问题......但我真的必须使用另一个变量(在上面的例子中:int level)吗?
  • 你为什么不想使用另一个变量?是因为内存成本吗?如果是这样,一个整数(原始类型)不会有任何危害。它的好处是封装了递归调用的深度。
  • 因为(也仅仅是因为)他们在面试中总是要求最简单的解决方案,但您的解决方案已经足够清晰和简单。
  • 我只是想知道递归级别(代码中的 int 级别)是否没有存储在其他地方。
  • “存储在其他地方”是什么意思?
【解决方案2】:

好吧,如果您使用 System.out.println,那么您应该能够使用 "\tThis is the..." 在大多数 java 输出窗口上缩进该行。我不明白这是否是您要求的。

如果你不知道你在哪个递归中,那么你就必须爬取 Thread.currentThread().getStackTrace()。

String s = "";
while(numRecursions --> 0) s += "\t";
System.out.println(s + "Something something something")

同样,如果您没有 numRecursions 变量,则必须执行类似的操作

    int numRecursions = 0;
    void a(){
        int temp = ++ numRecursions;
        String s = "";
        while(temp --> 0) s += "\t";
        System.out.println(s + "This is a recursion level");
        //code
        numRecursions--;
    }

【讨论】:

  • 标签的数量应该显示递归树的“深度”。
  • 是的,但技术上如何?那是我的问题。如果你不想,你不必想出一个解决方案,给我一些提示。
【解决方案3】:

在您的输出函数中包含一个前缀字符串参数。
每次调用函数时都传入前缀 +“”。 示例:

public void output(String prefix){
  // Whenever you print, start with prefix
  System.out.println(prefix + ...);

  // When you call your recursive method
  String childPrefix = prefix+"  ";
  output(childPrefix);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 2012-10-26
    • 2017-05-09
    相关资源
    最近更新 更多