数据结构-返回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;
    }
}
相关推荐
虹科网络安全11 小时前
艾体宝洞察 | 不止步于缓存 - Redis 多数据结构平台的演进与实践
数据结构·redis·缓存
ajole11 小时前
C++学习笔记——stack和queue
开发语言·数据结构·c++·笔记·学习·stl·学习方法
ValhallaCoder11 小时前
Day51-图论
数据结构·python·算法·图论
苦藤新鸡11 小时前
24.判断回文链表
数据结构·链表
进击的荆棘12 小时前
优选算法——双指针
数据结构·算法
努力努力再努力wz12 小时前
【Linux网络系列】:JSON+HTTP,用C++手搓一个web计算器服务器!
java·linux·运维·服务器·c语言·数据结构·c++
魂梦翩跹如雨12 小时前
死磕排序算法:手撕快速排序的四种姿势(Hoare、挖坑、前后指针 + 非递归)
java·数据结构·算法
鱼跃鹰飞1 天前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
好评1241 天前
【C++】二叉搜索树(BST):从原理到实现
数据结构·c++·二叉树·二叉搜索树
程序猿炎义1 天前
【Easy-VectorDB】Faiss数据结构与索引类型
数据结构·算法·faiss