來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof
寫一個函式,輸入 n ,求斐波那契(Fibonacci)數列的第 n 項(即 F(N)),斐波那契數列的定義如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契數列由 0 和 1 開始,之后的斐波那契數就是由之前的兩數相加而得出,
答案需要取模 1e9+7(1000000007),如計算初始結果為:1000000008,請回傳 1,
示例 1:
輸入:n = 2
輸出:1
示例 2:
輸入:n = 5
輸出:5
第一種解法:
將每次計算出來的結果存入hashmap中
class Solution {
private Map<Integer,Integer> storgefib =new HashMap<>();
public int fib(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
if(null != storgefib.get(n)){
return storgefib.get(n);
}else{
int result = (fib(n-1)+fib(n-2))%1000000007;
storgefib.put(n,result);
return result;
}
}
}

第二種方式,從底部向上,使用回圈求解
class Solution {
public int fib(int n){
int result = 0;
int pre = 1;
int prePre =0;
if(n == 0) return 0;
if(n == 1) return 1;
if(n >= 2){
for(int i = 2;i <= n; i++){
result = (pre+prePre)%1000000007;
prePre = pre;
pre = result;
}
}
return result;
}
}

解答程序同爬樓梯:具體參考這里:https://blog.csdn.net/weixin_43304253/article/details/122269352
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/400473.html
標籤:其他
上一篇:leetcode每日一題2022. 將一維陣列轉變成二維陣列 2022年從2022題開始 由1到2我相信咱們會更好
下一篇:2021年 - 年終總結
