【问题标题】:Can anyone explain how does the following recursion work?谁能解释以下递归是如何工作的?
【发布时间】:2014-11-07 19:30:36
【问题描述】:

我无法理解以下递归代码:

public class recursive {
    public static void main(String[] args){ 
        helper(0) ;
    }

    public static void helper(int i){
        int a=3;
        if(i==a){
            System.out.println("yes:"+i);
            return;
        }else{
            for(;i<a;i++){ 
                System.out.println("no:"+i);
                helper(i+1);
                System.out.println("end:"+i);
            }
        }
    }         
}

输出如下:

no:0
no:1
no:2
yes:3
end:2 //why this is 2?
end:1 //why this is 1?
no:2
yes:3
end:2
end:0
no:1
no:2
yes:3
end:2
end:1
no:2
yes:3
end:2

我不明白为什么第一个结尾是 2。谁能解释一下这个简单程序中的递归是如何工作的?

【问题讨论】:

    标签: java recursion


    【解决方案1】:

    试试

    public static void helper(int i){
        int a=3;
        if(i==a){
            System.out.println("yes:"+i);
            return;
        }else{
            System.out.println("no:"+i);
            helper(i+1);
        }
    }  
    

    递归的一个想法是消除循环

    【讨论】:

    • 我明白是否没有循环。但是当代码和我提供的代码一样时,我会感到困惑。
    • 因为helper 在打印yes 之前不会返回打印end。尝试使用铅笔和纸来跟随流程。
    • 我不明白的是为什么它返回到 i==2 的循环,然后直接返回到 i==1 的循环而不继续循环 i==2 中的任何内容?跨度>
    【解决方案2】:

    helper 的每次调用都有自己的本地值i

    所以当i==2,并且你调用helper(i+1),下一个对helper的调用有i==3,但是当它返回时,它会回到之前的helper调用,为此i==2

    【讨论】:

    • 感谢您的回答。所以它回到以前的助手,i==2。那么,为什么它会返回 i=1 呢?作为 end:1?为什么它不停留在 end:2 直到 i==3?
    • @b1694621 回到前一个助手后,又转到前一个助手,为此i==1
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多