解释递归输出

问题描述 投票:0回答:1
public class Main {
    public static void main(String[] args) {
        splitIt(1, 3);
    }

    public static void splitIt(int id, int n) {
        if (n > 0) {
            splitIt(id + 1, n - 1);
            System.out.println(id + "=" + n);
            splitIt(id + 1, n - 1);
        }
    }
}

当我运行此代码时,我得到下面的输出,但我不明白为什么以及如何得到该输出。如果有人可以解释一下,我们将不胜感激。

3=1

2=2

3=1

1=3

3=1

2=2

3=1

我尝试使用调试器,但我仍然不明白。

java recursion
1个回答
0
投票

您需要使用

id
n
制作图表并遵循逻辑。每次拨打电话时,记下这些值。一旦调用,该方法将不会返回,直到
n <= 0
,这是在 void 方法末尾隐式调用的(或者如果需要,更早不返回值)。

尝试使用附加的打印语句运行以下命令,看看发生了什么。

*'d
打印语句是您将打印在原始代码中打印的值的语句。

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

 public static void splitIt(int id, int n) {
     if (n > 0) {
         System.out.printf("before call1 - id = %d, n = %d%n", id, n);
         splitIt(id + 1, n - 1); // call1
         System.out.printf("*return from  call1 - id = %d, n = %d%n", id, n);
         System.out.println("making call2");
         System.out.printf("before call2 - id = %d, n = %d%n", id, n);
         splitIt(id + 1, n - 1); // call2
         System.out.printf("after call2 - id = %d, n = %d%n", id, n);
     }
     System.out.println("return since n <= 0");
}
© www.soinside.com 2019 - 2024. All rights reserved.