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 +