斐波那契數列的記憶化搜尋與動態規劃解法 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]; }};