递归输出

时间:2017-03-26 12:20:36

标签: java recursion output

这是我对递归问题的以下代码

是否有人能够告诉我输出结果是24?

为了证明我有多困惑,我认为输出将是6,12,20,1

package Examples;

public class QuestionDemo {

public static void main(String[] args) {

    System.out.println(recCall(2));
}

public static int recCall(int num) {

    if (num == 5) {
        return 1;
    } else {
        return num * recCall(++num);
    }

}
}

5 个答案:

答案 0 :(得分:2)

你有4个递归调用 第一个你打电话给recCall(2) 然后recCall(3),recCall(4)和recCall(5) recCall(5)返回1 recCall(4)返回4 * 1 recCall(3)返回3 * 4 * 1 recCall(2)返回2 * 3 * 4 * 1 = 24

答案 1 :(得分:2)

recCall(int num):

recall(2)
    |       | 
   2 *    recall(3)
              |       |
              3 *  recall(4)
                      |         |
                      4 *    recall(5)
                                |
                                1           



recall(2) = 24
            |       |
            2 *   12 = 24
                    |      |
                    3 *    4 = 12
                           |       |
                           4 *     1 = 4
                                   |
                                   1                                                 

答案 2 :(得分:1)

此递归采用自下而上方法。首先要深入找到基本案例的值,然后才能获得其他递归调用的值。

这就是您获得输出 = 24:

的原因
                                       _
                                      /|\ 
                                     / | \
recCall(4) = 4 * recCall(5) = 4  +  /  |  \ // recCall(5) is your base case.
recCall(3) = 3 * recCall(4) = 12 +     |
-----------------------------------    |
recCall(2) = 2 * recCall(3) = 24       | // This was your first call to the recursive function.

您不会遍历值,而是添加全部。

答案 3 :(得分:1)

因为您正在使用recCall(++num),并且您正在使用pre-increment运算符,它会在调用方法之前增加值。

请阅读++ pre increment如何在java中工作: - How do the post increment (i++) and pre increment (++i) operators work in Java?

所以你的递归调用将如下所示

 f(2)= 2*f(3)=2*12 = 24.
        f(3)=3*f(4)= 3*4=12
            f(4)=4*f(5) = 4*1
                f(5)= 1

因此它返回24。

答案 4 :(得分:0)

是的,如果您尝试移动召回(++ num)并将新号码设为++num,那么结果将为= 2 * 3 * 4,而在5中它将返回1,因此{{1} }。

相关问题