LeetCode刷题笔记-动态规划-day1

LeetCode刷题笔记-动态规划-day1

509. 斐波那契数

1.题目

原题链接:509. 斐波那契数

image-20220205082819912

2.解题思路

可以用dp数组递推做,这里直接用变量代替数组节省空间。

3.代码

class Solution {
    
    
public:
    int fib(int n) {
    
    
        int a=0,b=1;
        while(n--){
    
    
            int c=a+b;
            a=b,b=c;
        }   
        return a;
    }
};

1137. 第 N 个泰波那契数

1.题目

原题链接:1137. 第 N 个泰波那契数

image-20220205082907484

2.解题思路

递推一遍即可。

3.代码

class Solution {
    
    
public:
    int tribonacci(int n) {
    
    
        int t1=0,t2=1,t3=1;
        if(n<2) return n;
        for(int i=3;i<=n;i++){
    
    
            int t=t3;
            t3=t1+t2+t3;
            t1=t2,t2=t;
        }
        return t3;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45966440/article/details/122799634