the memory search and dynamic programming solution of Fibonacci sequence C + + implementation and related case analysis (leetcode70-stair climbing)
Recursive analytic formula for Fibonacci series: F (N) =f (n-1) +f (n-2)
the solution of ordinary no optimization
#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;
}
using a Memory search method for Top-down optimization
#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;
}
Solution of bottom-up Optimization using dynamic programming
#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 Related Issues
Climbing Stairs
You are are climbing a stair case. It takes n steps to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can your climb to the top?
Note: Given n'll be a positive integer.
Example 1:
Input:2
Output: 2
Explanation: There are two
ways to the top. 1.1 Step + 1 Step
2.2 steps
Example 2:
Input:3
Output: 3
Explanation: There are three
ways to the top. 1.1 Step + 1 Step + 1 Step
2.1 Step + 2 steps
3.2 Steps + 1 Step
Dynamic Programming is a 0 (n) time complexity with a memory search, but dynamic programming is a little faster than a memory search, so the problem is solved by dynamic programming, which is basically exactly the same as the Fibonacci sequence.
class Solution {public:int climbstairs (int n) {vector<int> memo = vector<int&
gt; (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]; }
};