斐波那契數列的記憶化搜尋與動態規劃解法 C++實現 以及相關案例分析(Leetcode70—爬樓梯)__C++

來源:互聯網
上載者:User
斐波那契數列的記憶化搜尋與動態規劃解法 C++實現 以及相關案例分析(Leetcode70—爬樓梯) Fibonacci數列的遞推解析式:F(n)=F(n-1)+F(n-2) 普通無最佳化的解法
#include <iostream>#include <bits/stdc++.h>using namespace std;int num=0;int Fibonacci(int n){    num++;    if(n==1||n==2)        return 1;    return Fibonacci(n-1)+Fibonacci(n-2);}int main(int argc, char *argv[]) {    int x=40;       x=Fibonacci(x);    cout<<x<<endl<<num<<endl;    return 0;}
使用記憶化搜尋自頂向下最佳化的解法
#include <iostream>#include <bits/stdc++.h>using namespace std;vector<int> memo;int num=0;int Fibonacci(int n){    num++;    if(n==1||n==2)        return 1;    if(memo[n]!=-1)        return memo[n];    memo[n]=Fibonacci(n-1)+Fibonacci(n-2);    return memo[n];}int main(int argc, char *argv[]) {    int x=40;       memo = vector<int>(x+1,-1);    x=Fibonacci(x);    cout<<x<<endl<<num<<endl;    return 0;}
使用動態規劃自底向上最佳化的解法
#include <iostream>#include <bits/stdc++.h>using namespace std;vector<int> memo;int main(int argc, char *argv[]) {    int x=40;       memo = vector<int>(x+1,-1);    memo[0]=0;    memo[1]=1;    for(int i=2;i<=x;i++)    {        memo[i]=memo[i-1]+memo[i-2];    }    cout<<memo[x]<<endl;    return 0;}
Leetcode相關問題 70. Climbing Stairs You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2Output:  2Explanation:  There are two ways to climb to the top.1. 1 step + 1 step2. 2 steps

Example 2:

Input: 3Output:  3Explanation:  There are three ways to climb to the top.1. 1 step + 1 step + 1 step2. 1 step + 2 steps3. 2 steps + 1 step
動態規劃雖然跟記憶化搜尋同樣是0(n)的時間複雜度,但是動態規劃會比記憶化搜尋稍微快一點,所以這道題就直接用動態規劃解出來了,跟斐波那契數列基本是一模一樣
class Solution {public:    int climbStairs(int n) {    vector<int> memo = vector<int>(n+1,-1);    memo[1]=1;    memo[2]=2;    for(int i=3;i<=n;i++)    {        memo[i]=memo[i-1]+memo[i-2];    }    return memo[n];    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.