跟踪递归方法

时间:2011-12-17 14:21:34

标签: java recursion

我发现理解递归的概念非常困惑。我试图追踪一个递归函数。有人可以帮帮我吗?

    public static int h(int n){
        if (n == 0)
            return 0;
        else
            return h(n-1)+1;
    }

写作时

int a = h(5);
System.out.println(a)

我不明白结果是如何产生的?

3 个答案:

答案 0 :(得分:8)

首先,如果您难以理解递归的概念,我认为以下链接可以帮助您:

您可以使用IDE上的调试工具来查看它的工作方式。您可以在Google上获取有关如何设置beakpoints并使用调试器逐步完成该程序的说明。

关于方法h,它将返回您作为输入提供的内容(如果它是正数或0)。也是大数字&否定数字将导致StackOverflowError。要了解其工作原理,您可以在方法中使用print语句。

public static int h(int n) {
    System.out.println("h(" + n + ")");
    if (n == 0) {
        System.out.println("value: 0");
        return 0;
    } else {
        System.out.println("going down");
        int temp = h(n - 1) + 1;
        System.out.println("h(" + n + ") --> " + temp);
        return temp;
    }
}

将输出:

h(5)
going down
h(4)
going down
h(3)
going down
h(2)
going down
h(1)
going down
h(0)
value: 0
h(1) --> 1
h(2) --> 2
h(3) --> 3
h(4) --> 4
h(5) --> 5

可以编辑上述输出以显示正常工作:

h(5)
|    going down
|----h(4)
|    |   going down
|    |---h(3)
|    |   |   going down
|    |   |---h(2)
|    |   |   |  going down
|    |   |   |--h(1)
|    |   |   |  |    going down
|    |   |   |  |----h(0)
|    |   |   |  |    |    value: 0 --> return 0;
|    |   |   |  |    h(1) --> 1 --> h(0) + 1 = 0 + 1 = 1
|    |   |   |  h(2) --> 2          h(1) + 1 = 1 + 1 = 2
|    |   |   h(3) --> 3             h(2) + 2 = 1 + 1 = 3
|    |   h(4) --> 4                 h(3) + 3 = 1 + 1 = 4
|    h(5) --> 5                     h(4) + 4 = 1 + 1 = 5

以下是方法h的非递归版本。

public static int nonh(int n) {
    int result = 0;
    for (int i = n; i > 0; i--) {
        result += 1;
    }

    return result;
}

希望有所帮助:)

答案 1 :(得分:4)

要在调试器中跟踪此递归调用,请在if语句上设置断点,然后运行程序。到达断点时:

  • 检查n
  • 的值
  • 查看调用堆栈窗口。

每次递归调用时,调用堆栈上的项数都会增加; n的值会减一。当您在呼叫深入多个级别时,单击呼叫堆栈上的不同项目。它会将您带到呼叫站点(即return h(n-1)+1)。您将能够在此堆栈级别检查n的值。

答案 2 :(得分:3)

尝试记录。或者,只是调试打印:

public static int h(int n){
    System.out.println("called h(" + n + ")");
    if (n == 0) {
        System.out.println("we know the result for 0, returning 0");
        return 0;
    } else {
        System.out.println("we don't know the result, calling for " + (n-1));
        int t = h(n-1);
        System.out.println("Found the result for " + (n-1) + 
                           ", calculating the result for " + n);
        return t + 1;
    }
}

对于n = 4,您将获得:

called h(4)
we don't know the result, calling for 3
called h(3)
we don't know the result, calling for 2
called h(2)
we don't know the result, calling for 1
called h(1)
we don't know the result, calling for 0
called h(0)
we know the result for 0, returning 0
Found the result for 0, calculating the result for 1
Found the result for 1, calculating the result for 2
Found the result for 2, calculating the result for 3
Found the result for 3, calculating the result for 4

希望它能给你一个线索 - 玩不同的算法,看看会发生什么。

此外,请尝试拨打h(-1) - 并享受乐趣!