递归简单使用

来源:互联网 发布:网络交流环境定义 编辑:程序博客网 时间:2024/06/03 19:21

递归: 在方法中直接、间接调用了方法本身

① 递归的优点:

业务问题解决的很优雅 只需要解决一个层次,其他层次问题就递归解决了。

② 递归的缺点

大量消耗栈内存空间,不能进行过深层次的递归否则 可能出现 栈溢出错误

③ 使用递归的要点

  1)不能过深的递归

  2)不能发散递归

  3)必须有结束条件

 

例1:

public class Demo {

        public static void main(String[] args) {

                int n = 10000;

                int y = f(n);

                System.out.println(y);

        }

        public static int f(int n){

                if(n==1){

                        return 1;

                }

                return  n + f(n-1);

        }

}

 

例2:

/**

 * 斐波那契 解决 

 * f(n) = f(n-1)+f(n-2) 并且 f(1)=1, f(2)=1;

 */

public class Demo {

        public static void main(String[] args) {

                System.out.println(f(10));

                System.out.println(f1(10));

                System.out.println(f(50));

                System.out.println(f1(50));

        }

        public static long f1(long n){//递归

                if(n==1 || n==2){

                        return 1;

                }

                return f1(n-1) + f1(n-2);

        }

        public static long f(long n){//循环

                long f1 = 1;

                long f2 = 1;

                long fn = 1;

                for(int i=3; i<=n; i++){

                        fn = f1+f2;

                        f1 = f2;

                        f2 = fn;

                }

                return fn;

        }

}

0 0
原创粉丝点击