Video

Latest

DP - 1. Fibonacci, 2. Factorial

509. Fibonacci Number
Easy

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).

 

Example 1:

Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

 

Constraints:

  • 0 <= n <= 30
Accepted
847,242
Submissions
1,237,724






Solution :




Approach - Recursion:

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


Approach - DP:

class Solution {
    public int fib(int n) {
        int[] f = new int[n+2];
        f[0] = 0;
        f[1] = 1;
        for(int i=2; i<=n; i++) {
            f[i]=f[i-1]+f[i-2];
        }
        return f[n];
    }
}




----------- X -----------


Factorial 
Basic Accuracy: 53.69% Submissions: 30344 Points: 1

Given a positive integer, N. Find the factorial of N.
 

Example 1:

Input:
N = 5
Output:
120
Explanation:
5*4*3*2*1 = 120

Example 2:

Input:
N = 4
Output:
24
Explanation:
4*3*2*1 = 24


Your Task:
You don't need to read input or print anything. Your task is to complete the function factorial() which takes an integer N as input parameters and returns an integer, the factorial of N.

 

Expected Time Complexity: O(N)
Expected Space Complexity: O(1)

 

Constraints:
0 <= N <= 18








Solution :







Approach - Recursion:

class Solution{
    public static long factorial(int n){
        if(n<2) return 1;
        return n*factorial(n-1);
    }
}


Approach - DP:

class Solution{
    long[] dp = new long[100];
    public long factorial(int n){
        if(n<2) return 1;
        else {
            if(dp[n]==0) {
                dp[n] = n*factorial(n-1);
            }
            return dp[n];
        }
    }
}



No comments