数据结构-返回n年后牛的数量

第一年农场有1只成熟的母牛A,往后的每年:

  1. 每一只成熟的母牛都会生一只母牛
  2. 每一只新出生的母牛都在出生的第三年成熟
  3. 每一只母牛永远不会死

返回N年后牛的数量。

抽象公式就是 F(N) = F(N-1) + F(N-3).

矩阵公式:

|F4, F3, F2| = |F3,F2,F1| * 3阶矩阵

|F5, F4, F3| = |F4,F3,F2| * 3阶矩阵

|F6, F5, F4| = |F5,F4,F3| * 3阶矩阵

通过3个公式求出3阶矩阵

java 复制代码
public class FibonacciProblem {
    public static void main(String[] args) {
        // 1,1,2,3,5,8,13
        int n = 19;
        System.out.println(c1(n));
        System.out.println(c3(n));

    }

    // 递归解
    public static int c1(int n){

        if (n < 0){
            return 0;
        }

        if (n == 1 || n == 2 || n == 3){
            return n;
        }

        return c1(n-1) + c1(n-3);
    }

    // 矩阵解
    public static int c3(int n){
        if (n < 1){
            return 0;
        }

        if(n == 1 || n == 2){
            return 1;
        }

        int[][] base = {
                {1,1,0},
                {0,0,1},
                {1,0,0}
        };

        int[][] res = matrixPower(base, n-3);

        //|F3,F2,F1| * (3阶矩阵的n-3次方)
        return 3*res[0][0] + 2*res[1][0] + res[2][0];
    }

    public static int[][] matrixPower(int[][] m, int p){
        int[][] res = new int[m.length][m[0].length];

        for (int i = 0; i < res.length; i++) {
            res[i][i] = 1; // 对角线
        }

        // res=矩阵中的1
        int[][] t = m; // 矩阵1次方
        for (; p != 0; p >>= 1){
             if((p&1) != 0){
                res = mulMatrix(res, t);
             }

             t = mulMatrix(t,t);
        }

        return res;
    }

    // 两个矩阵相乘.  第一个矩阵的行数等于第二个矩阵的列数
    public static int[][] mulMatrix(int[][] m1, int[][] m2){
        int res[][] = new int[m1.length][m2[0].length];
        for (int i = 0; i < m1.length; i++) {
            for (int j = 0; j < m2[0].length; j++) {
                for (int k = 0; k < m2.length; k++) {
                    res[i][j] += m1[i][k] * m2[k][j];
                }
            }
        }
        return res;
    }
}
相关推荐
理想青年宁兴星1 小时前
【数据结构】字符串与JSON字符串、JSON字符串及相应数据结构(如对象与数组)之间的相互转换
java·数据结构·json
轩源源11 小时前
函数模板(初阶)
数据结构
想拿大厂offer11 小时前
【数据结构】第八节:链式二叉树
c语言·数据结构
Renascence.40912 小时前
力扣--649.Dota2参议院
java·数据结构·算法·leetcode
_Power_Y13 小时前
浙大数据结构:02-线性结构3 Reversing Linked List
数据结构
萌新小码农‍14 小时前
matlab基本语法
网络·数据结构·matlab
巧手打字通14 小时前
数据结构之美-深入理解树形结构
数据结构·树形结构
Crossoads15 小时前
【数据结构】带你初步了解排序算法
c语言·开发语言·数据结构·算法·排序算法
酷酷学!!!15 小时前
C++: set与map容器的介绍与使用
开发语言·数据结构·c++·算法
Andrew_Xzw15 小时前
复现OpenVLA:开源的视觉-语言-动作模型及原理详解
数据结构·c++·python·深度学习·算法·开源