C# Practice for Fianl 0x00

Prac1

描述

大家都知道斐波那契数列,现在要求输入一个正整数 n ,请你输出斐波那契数列的第 n 项。

斐波那契数列是一个满足 fib(x)={1fib(x−1)+fib(x−2)​x=1,2x>2​ 的数列

数据范围:1≤n≤40

要求:空间复杂度 O(1),时间复杂度 O(n) ,本题也有时间复杂度 O(logn) 的解法

using System;
using System.Collections.Generic;


class Solution {
   
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */
    int Fib(int n, int[] f){
   
        if(f[n] != -1) return f[n];
        return Fib(n - 1, f) + Fib(n - 2, f);
    }
    public int Fibonacci (int n) {
   
        // write code here
        int[] f = new int[n + 1];
        for(int i = 0; i <= n; i ++){
   
            f[i] = -1;
        }
        f[1] = 1;
        f[2] = 1;
        return Fib(n, f); 
    }
}

上面的代码漏掉了记忆化搜索,多了很多重复子计算 :

using System;
using System.Collections.Generic;


class Solution {
   
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */
    int Fib(int n, int[] f){
   
        if(f[n] != -1) return f[n];
        return f[n] = Fib(n - 1, f) + Fib(n - 2, f);
    }
    public int Fibonacci (int n) {
   
        // write code here
        int[] f = new int[n + 1];
        for(int i = 0; i <= n; i ++){
   
            f[i] = -1;
        }
        f[1] = 1;
        f[2] = 1;
        return Fib(n, f); 
    }
}

事实上, O ( log ⁡ n ) O(\log n) O(logn) 时间复杂度内求斐波那契数列需要用到矩阵快速幂。

还要注意下面,

using System;
using System.Collections.Generic;


class Solution
{
   
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */ 
    void test(int[] f)
    {
   
        f[1] = 0;
    }
    public int Fibonacci(int n)
    {
   
        // write code here
        int[] f = new int[n +
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值