zoukankan      html  css  js  c++  java
  • 兔子问题,斐波纳契数列

    题目:古典问题(斐波纳契数列):有一对兔子,从出生后3个月起每个月都生一对兔子,小兔子长到第三个月又会生一对兔子,假如兔子都不死,问每个月兔子总数?
    分析规律:1 1 2 3 5 8 13 21…
    从第二个月以后每个月兔子总数是前两个月兔子总数之和


    1.递归算法:效率灰常低

    package com.math.forth;
    
    /***
     * 古典问题(斐波纳契数列):有一对兔子,从出生后3个月起每个月都生一对兔子,小兔子长到第三个月又会生一对兔子,假如兔子都不死,问每个月兔子总数? 分析:规律
     * 1 1 2 3 5 8 13 21... 从第二个月以后每个月兔子总数是前两个月兔子总数之和
     * 
     * @author wql
     *
     */
    public class Math01 {
        public static void main(String[] args) {
            int month = 2;// 给一个月数
            int sum;// 兔子总数
            for (int i = 1; i <= month; i++) {
                sum = method(i);
            }
            System.out.println(sum);
        }
    
        public static int method(int month) {
            if (month <= 2) {
                return 1;
            } else {
                return method(month - 1) + method(month - 2); // 递归:这种方法效率非常低
            }
        }
    }
    

    2.利用时间的复杂度逻辑计算,效率灰常高(int类型都不可以满足运算)

    package com.math.forth;
    /**
     * @author wql
     *
     */
        public class Math01 {
            public static long method2(int month){
            long a=1;  
            long b=1;  
            long c=0;  
            if(month==1||month==2)  
            {  
                return 1;  
            }  
            else  
            {  
                for(int i=3;i<=month;i++)  
                {  
                    c=a+b;  
                    b=a;  
                    a=c;  
                }  
                return a;  
            }  
        }
        public static void main(String[] args) {
            int month=100;//给一个月份
            long sum=method2(100);
            System.out.println(sum);
        }
    }
  • 相关阅读:
    清北学堂总结(未完待续。。。。。。。)
    洛谷p3372 线段树模版
    SPFA模版
    线段树 洛谷 p1531 I hate it(I hate it too)
    01 背包找装满方案数 洛谷 p1164 小a点菜
    01 找最大剩余体积 洛谷1049 装箱问题
    洛谷 p1880 石子合并 区间dp
    石子合并 最大值
    清北学堂入学测试d
    HTML 标记 3 —— 框架
  • 原文地址:https://www.cnblogs.com/wangqilong/p/8279779.html
Copyright © 2011-2022 走看看