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));
    }
}
上一篇:LeetCode 312. 戳气球


下一篇:1240. Tiling a Rectangle with the Fewest Squares