数据结构-返回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;
    }
}
相关推荐
老师我太想进步了20261 天前
【数据结构-8】栈的实现
c语言·数据结构·算法
【心态好不摆烂】2 天前
数据结构基础精讲3
数据结构·算法
岑梓铭2 天前
《考研408数据结构》第七章(B树 和 B+树)复习笔记
数据结构·笔记·b树·考研·408
岑梓铭2 天前
《考研408数据结构》第八章(排序)复习笔记
数据结构·笔记
nice_lcj5203 天前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
꧁细听勿语情꧂3 天前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
Pniubi4 天前
关于算法用现成数据结构和手撕
数据结构
老师我太想进步了20264 天前
【数据结构-6】算法美学之单链表(1)
数据结构·算法
希望我万事顺遂4 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode
꧁细听勿语情꧂4 天前
二叉树余题,排序、直接插入排序、希尔排序
c语言·开发语言·数据结构·算法