leetcode 509. 斐波那契数

 

 

 

方法一:递归

使用递归计算给定整数的斐波那契数。

 

效率最差但是最简单的方法,会重复计算,就不实现了。

方法二:记忆化自底向上的方法

 

方法三:自底向上进行迭代

方法四:矩阵求幂 

 

public class Solution 
{
    /*
    //数组 方法二:记忆化自底向上的方法
    public int Fib(int N) 
    {
        if(N < 2)
            return N;
        int[] resArray = new int[N + 1];
        resArray[0] = 0;
        resArray[1] = 1;
        for(int i = 2; i <= N; i++)
        {
            resArray[i] = resArray[i - 1] + resArray[i - 2];
        }
        return resArray[N];
    }
    */
    /* 滑动变量  方法三:自底向上进行迭代
    public int Fib(int N) 
    {
        if(N < 2)
            return N;
        int pre = 1;
        int prepre = 0;
        int current = 0;
        for(int i = 2; i <= N; i++)
        {
            current = pre + prepre;
            prepre = pre;
            pre = current;
        }
        return current;
    }
    */
    //方法四:矩阵求幂 
    public int Fib(int N)
    {
        if (N <= 1) {
          return N;
        }
        int[,] A = new int[,]{{1, 1}, {1, 0}};
        matrixPower(A, N-1);

        return A[0,0];
    }

    void matrixPower(int[,] A, int N) {
        if (N <= 1) {
          return;
        }
        matrixPower(A, N/2);
        multiply(A, A);

        int[,] B = new int[,]{{1, 1}, {1, 0}};
        if (N%2 != 0) {
            multiply(A, B);
        }
    }

    void multiply(int[,] A, int[,] B) {
        int x = A[0,0] * B[0,0] + A[0,1] * B[1,0];
        int y = A[0,0] * B[0,1] + A[0,1] * B[1,1];
        int z = A[1,0] * B[0,0] + A[1,1] * B[1,0];
        int w = A[1,0] * B[0,1] + A[1,1] * B[1,1];

        A[0,0] = x;
        A[0,1] = y;
        A[1,0] = z;
        A[1,1] = w;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值