public static void main(String[] args) {
test1();
}
public static void test1(){
System.out.println("----test1----");
test1();
}
public static void test2(){
System.out.println("----test2----");
test3();
}
private static void test3() {
test2();
}
递归算法三要素:
- 递归的公式:f(n) = f(n - 1) * n
- 递归的终结点:f(1)
- 递归的方向必须走向终结点
- 案例:用方法递归计算阶乘
public static void main(String[] args) {
System.out.println(f(5));
}
public static int f(int n) {
if(n == 1){
return 1;
}else{
return f(n - 1) * n;
}
}
- 递归求1-n的和
public static void main(String[] args) {
System.out.println(f(5));
}
public static int f(int n) {
if(n == 1){
return 1;
}else{
return f(n - 1) + n;
}
}
- 猴子吃桃问题
public static void main(String[] args) {
//猴子吃桃问题:后一天吃的都是前一天桃子数量的一半再减一个
//f(x) - f(x) / 2 - 1 = f(x + 1) x是天数
//2f(x) - f(x) - 2 = 2f(x + 1)
//f(x) = 2f(x + 1) + 2
System.out.println(f(1));
System.out.println(f(2));
System.out.println(f(3));
System.out.println(f(4));
System.out.println(f(5));
}
public static int f(int x) {
if(x == 10){
return 1;
}else{
return 2 * f(x + 1) + 2;
}
}
标签:递归,void,System,public,static,println,方法,黑马,out
From: https://blog.csdn.net/m0_56508224/article/details/139335261