LeetCode 509.斐波那契数列

一,题目描述

二,问题分析

非常经典的例题,可以采用递归和动态规划两种思路,递归公式显而易见 F(N) = F(N-1)+F(N-2)  N>=2

三,代码阶段

1.普通递归

class Solution {
public:
    int fib(int N) {
        if(N==0){
            return 0;
        }
        if(N == 1){
            return 1;
        }
        else return fib(N-1) + fib(N-2);
    }
};

2.动态规划

采用一维数组记录,memo[i]表示F(i)

class Solution {
public:
    int fib(int N) {
        vector<int> memo(N+1);
        if(N==0){
            return 0;
        }else if(N==1){
            return 1;
        }
        else{
            memo[0] = 0;
            memo[1] = 1;
            for(int i=2;i<=N;i++){
                memo[i] = memo[i-1] + memo[i-2];
            }
        }
        return memo[N];
    }
};
发布了54 篇原创文章 · 获赞 14 · 访问量 3573

猜你喜欢

转载自blog.csdn.net/q2511130633/article/details/105254639