A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 374856298 中级黑马   /  2015-4-28 21:57  /  437 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

JAVA经典算法40例
【程序1】   题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?  
1.程序分析:   兔子的规律为数列1,1,2,3,5,8,13,21....  
public class exp2{
        public static void main(String args[]){
                int i=0;
                for(i=1;i<=20;i++)
                        System.out.println(f(i));
        }
        public static int f(int x)
        {
                if(x==1 || x==2)
                        return 1;
                else
                        return f(x-1)+f(x-2);
        }
}

public class exp2{
        public static void main(String args[]){
                int i=0;
                math mymath = new math();
                for(i=1;i<=20;i++)
                        System.out.println(mymath.f(i));
        }

}
class math
{
        public int f(int x)
        {
                if(x==1 || x==2)
                        return 1;
                else
                        return f(x-1)+f(x-2);
        }
}

1 个回复

倒序浏览
本题考察了裴波纳契数数列,主要利用递归思想来解决问题,递归就是自己调用自己,通过设定一个结束条件,然后再从结束调节往前推导,在本题中,结束条件为x==1 || x==2,满足条件则返回1,否则返回F(x-1)+f(x-2)。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马