public class Recursion01 {
public static void main(String[] args){
T t=new T();
t.test(4);
}
}
class T{
public void test(int n){
if (n>2){
test(n-1);
}
System.out.println("n="+n);
}
}
1.
思路分析:
1. 当n=1时,斐波那契数是1
2.当n=2时,斐波那契数是1
3.当n>=3时,斐波那契数是前两个数之和
public class Recursion02 {
public static void main(String[] args){
T1 tt=new T1();
// tt.Fibinacci(5);
System.out.println(tt.Fibinacci(7));
}
}
class T1 {
public int Fibinacci(int n) {
if (n >= 1) {
if (n == 1 || n == 2) {
return 1;
} else {
return Fibinacci(n - 1) + Fibinacci(n - 2);
}
} else {
System.out.println("输入错误");
return -1;
}
}
}
2.猴子吃桃
思路分析:逆推法
1.day=10时,有1个桃子
2.day=9时,有(day10+1)*2=4
3.day=8时,有(day9+1)*2=10
public class monkeyEatPeach {
public static void main(String[] args){
T2 t2=new T2();
int day=9;
int pecahnum=t2.peach(day);
if (pecahnum!=1){
System.out.println("第"+day+"天有"+pecahnum+"个桃子");
}
}
}
class T2 {
public int peach(int day){
if (day==10){
return 1;
}else if (day>=1&&day<=9){
return (peach(day+1)+1)*2;
}else {
return -1;
}
}
}