18. java面向对象 - 递归

一、案例

public class Recursive {
    public int sumRec(int num){
        if(num == 1){
            return 1;
        }else {
            return num + sumRec(num -1);
        }
    }
}


class RecTest{
    public static void main(String[] args) {
        Recursive rec = new Recursive();
        System.out.println(rec.sumRec(100)); // 5050
    }
}
/*
    已知一个数列:f(0)=1,f(1)=4,f(n+2)=2*f(n-1)+f(n)
    其中n大于0整数,求f(10)
 */

public class Recursive {
    public int f(int n) {
        if (n == 0) {
            return 1;
        } else if (n == 1) {
            return 4;
        } else {
            return 2 * f(n - 1) + f(n - 2);
        }
    }
}

class RecTest {
    public static void main(String[] args) {
        Recursive rec = new Recursive();
        System.out.println(rec.f(10));
    }
}
posted @ 2019-12-30 19:50  qi.hu  阅读(141)  评论(0编辑  收藏  举报