有限递归VS无穷递归

无穷递归

public class Test1 {

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

    public static void main(String[] args) {
        System.out.println("infinite recursion~~");
        System.out.println(f(5));
    }

}

假设输入的是正整数,n / 3 + 1,这个值肯定大于等于1,但 f(1) = f(1/3+1)+1-1 = f(1)……

所以最终就会陷入无穷递归,导致StackOverflow。。。

有限递归

public class Test2 {

    public static int f(int x) {
        if(x == 0) {
            return 0;
        } else {
            return 2 * f(x - 1) + x * x;
        }
    }

    public static void main(String [] args) {
        System.out.println("f(5) = " + f(5));
    }

}

假设输入的是正整数,这个递归算法就能逐步简化问题,每次只是减1,最终就能归到x==0时的终止条件。。。

发布了599 篇原创文章 · 获赞 1211 · 访问量 43万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104509010
今日推荐