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);
        }
    }
  • 相关阅读:
    LeetCode 842. Split Array into Fibonacci Sequence
    LeetCode 1087. Brace Expansion
    LeetCode 1219. Path with Maximum Gold
    LeetCode 1079. Letter Tile Possibilities
    LeetCode 1049. Last Stone Weight II
    LeetCode 1046. Last Stone Weight
    LeetCode 1139. Largest 1-Bordered Square
    LeetCode 764. Largest Plus Sign
    LeetCode 1105. Filling Bookcase Shelves
    LeetCode 1027. Longest Arithmetic Sequence
  • 原文地址:https://www.cnblogs.com/wangqilong/p/8279779.html
Copyright © 2011-2022 走看看