π One-stop destination for all your technical interview Preparation π
The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n
, calculate F(n)
.
F(0) = 0
and F(1) = 1
.F(n) = F(n - 1) + F(n - 2)
for n > 1
.F(n)
by using the above formula in a recursive way.class Solution {
public:
int fib(int n)
{
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
};
n + 1
and fill it with -1
to indicate that we have not calculated the value for that index yet.class Solution {
private:
int fibHelper(int n, vector<int>& dp)
{
if (n <= 1) return n;
if (dp[n] != -1) return dp[n]; // Return the Value, if already calculated
return dp[n] = fibHelper(n - 1, dp) + fibHelper(n - 2, dp); // Calculate and store the value
}
public:
int fib(int n)
{
vector<int> dp(n + 1, -1);
return fibHelper(n, dp);
}
};
dp[0]=0
and dp[1]=1
in dp array or vector.dp[i] = dp[i - 1] + dp[i - 2]
class Solution {
public:
int fib(int n)
{
if(n<=1) return n; // Base condition require, if n=0 the dp[1] will give error
vector<int> dp(n + 1, -1);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
};
current value
by adding previous
and previous's previous value
.n
elements in an array, we can use prev2
to store previousβs previous value and prev
to store previous value.curr = prev + prev2
.prev2
and curr in prev
.class Solution {
public:
int fib(int n)
{
if (n <= 1) return n;
int prev2 = 0, prev = 1;
for (int i = 2; i <= n; i++) {
int curr = prev + prev2;
prev2 = prev;
prev = curr;
}
return prev;
}
};