递归语句调用另一个递归语句?

时间:2014-02-04 06:06:05

标签: java recursion static-methods

public class Recursive_Prob
{    
    public static void main(String[] args)    
    {    
        out.print("\f");   
        out.print(m(4));   
    }   
    public static int m(int a)   
    {   
        if (a < 0)    
            return 0;    
        else    
            return m(a-2) + n(a-1);    
    }       
    public static int n(int b)     
    {     
        if (b <= 0)    
            return 0;     
        else     
            return 1 + n(b-1);     
    }       
}    

我有一个问题,询问使用m调用方法out.print(m(4));时的输出是什么我尝试了解0,但答案是{{1}当我运行代码时。我最终得到4 m(a-2)并且该部分是正确的,但使用相同的逻辑,0也是n(a-1),所以显然我做错了。有人可以解释这是如何工作的?

6 个答案:

答案 0 :(得分:5)

找出答案的最佳方法是绘制递归树。让我试试:

                    m(4)
                     /\
                    /  \
                   m(2) \
                   /\   n(3)
                  /  \     \
                 m(0) \     \
                 /\   n(1)  1+n(2)
                /  \    \      \
              m(-2) \  1+n(0)   \
               /   n(-1)   \   1+n(1)
              0       \     0      \   
                       0            \
                                   1+n(0)
                                      \
                                       0

添加它们,结果应为4

答案 1 :(得分:4)

这是一步一步计算:

m(4) = m(2) + n(3)
     = m(0) + n(1) + n(3)
     = m(-2) + n(-1) + n(1) + n(3)
     = 0 + 0 + 1 + n(0) + 1 + n(2)
     = 0 + 0 + 1 + 0 + 1 + 1 + n(1)
     = 0 + 0 + 1 + 0 + 1 + 1 + 1 + n(0)
     = 0 + 0 + 1 + 0 + 1 + 1 + 1 + 0
     = 4

答案 2 :(得分:1)

enter image description here

如果将所有红线相加,则等于4。

树的左侧实际上是m(-2),但我没有包含它,因为它导致0.

答案 3 :(得分:0)

1 + n(b-1)函数中有n(int b)。调用n(a-1)将对n(int b)进行4次递归调用并返回4

答案 4 :(得分:0)

让我们分解一下:

m(4) = m(2) + n(3);
m(2) = m(0) + n(1);
m(0) = m(-2) + n(-1);
     =   0   +   0

n(3) = 1 + n(2);
n(2) = 1 + n(1);
n(1) = 1 + n(0);
     = 1 +  0 
n(1) = 2

让我们替换所有的值:

n(2) = 1 + n(1) = 2
n(3) = 1 + n(2) = 3

m(2) = 0 + 1;
m(4) = 1 + 3 = 4

答案 5 :(得分:0)

first call m(4) +n(3)
second call m(2) + n(1)
third call m(0) +n(-1)
fourth call m(-2) + n(-3)
the function m returns 0
so the fourth call becomes 0+n(-3)
n(-3) also returns 0 so overall the function in fourth call will return 0
now in third call we have m(0) = 0, now n(-1) will also return 0,so overall 
the third call will return 0 to second call.
now in second call m(2) = 0 , and now it call n(1) .. n(1) will return 1+n(0)=>1
so second call will return 0+1 to first call 
now in first call m(4) =1 ,now it will call n(3).
now in n(3)..it will call 1+n(2) => 1+n(1) => 1+n(0) =>1 so n(3) will return 3
so overall result is 1+3 =>4