Number of Unique BST with a given key | Dynamic Programming - GeeksforGeeks

08 Apr, 2022
Given N, Find the total number of unique BSTs that can be made using values from 1 to N. Examples:  
Input: n = 3 
Output: 5
For n = 3, preorder traversal of Unique BSTs are:
1. 1 2 3
2. 1 3 2
3. 2 1 3
4. 3 1 2
5. 3 2 1

Input: 4 
Output: 14
 
In the previous post a O(n) solution has been discussed. In this post we will discuss a solution based on Dynamic Programming. For all possible values of i, consider i as root, then [1....i-1] numbers will fall in the left subtree and [i+1....n] numbers will fall in the right subtree. So, add (i-1)*(n-i) to the answer. The summation of the products will be the answer to the number of unique BST. Below is the implementation for above approach:  
C++
C
Java
Python3
C#
PHP
// C++ code to find number of unique BSTs// Dynamic Programming solution#include <bits/stdc++.h>using namespace std; // Function to find number of unique BSTint numberOfBST(int n){     // DP to store the number of unique BST with key i    int dp[n + 1];    fill_n(dp, n + 1, 0);     // Base case    dp[0] = 1;    dp[1] = 1;     // fill the dp table in bottom-up approach.    for (int i = 2; i <= n; i++) {        for (int j = 1; j <= i; j++) {             // n-i in right * i-1 in left            dp[i] = dp[i] + (dp[i - j] * dp[j - 1]);        }    }     return dp[n];} // Driver Codeint main(){    int n = 3;    cout << "Number of structurally Unique BST with " <<    n << " keys are : " << numberOfBST(n) << "\n";     return 0;}// This code is contributed by Aditya kumar (adityakumar129)
// C code to find number of unique BSTs// Dynamic Programming solution#include <stdio.h> // DP to store the number of unique BST with key iint dp[20]; // Function to find number of unique BSTint numberOfBST(int n){       // Base case    if (n <= 1)        return 1;       // In case if the value is already present in the array    // just return it and no need to calculate it    if (dp[n])        return dp[n];    for (int i = 1; i <= n; i++)        dp[n] += numberOfBST(i - 1) * numberOfBST(n - i);    return dp[n];} // Driver Codeint main(){    int n = 3;    printf("Number of structurally Unique BST with %d keys are %d", n, numberOfBST(n));    return 0;} // This code is contributed by Aditya kumar (adityakumar129)
// Java code to find number// of unique BSTs Dynamic// Programming solutionimport java.io.*;import java.util.Arrays;  class GFG {  public static int dp[] = new int[20];    static int numberOfBST(int n)    {        // Base case        if (n <= 1)            return 1;        // In case if the value is already present in the        // array just return it and no need to calculate it        if (dp[n]>0)            return dp[n];        for (int i = 1; i <= n; i++)            dp[n] += numberOfBST(i - 1) * numberOfBST(n - i);        return dp[n];    }     // Driver Code    public static void main(String[] args)    {        int n = 3;        System.out.println("Number of structurally " + "Unique BST with " + n                           + " keys are : " + numberOfBST(n));    }} // This code is contributed by Aditya kumar (adityakumar129)
# Python3 code to find number of unique# BSTs Dynamic Programming solution # Function to find number of unique BSTdef numberOfBST(n):     # DP to store the number of unique    # BST with key i    dp = [0] * (n + 1)     # Base case    dp[0], dp[1] = 1, 1     # fill the dp table in top-down    # approach.    for i in range(2, n + 1):        for j in range(1, i + 1):             # n-i in right * i-1 in left            dp[i] = dp[i] + (dp[i - j] *                             dp[j - 1])     return dp[n] # Driver Codeif __name__ == "__main__":     n = 3    print("Number of structurally Unique BST with",                   n, "keys are :", numberOfBST(n)) # This code is contributed# by Rituraj Jain
// C# code to find number// of unique BSTs Dynamic// Programming solutionusing System; class GFG{    static int numberOfBST(int n)    {     // DP to store the number    // of unique BST with key i    int []dp = new int[n + 1];         // Base case    dp[0] = 1;    dp[1] = 1;     // fill the dp table in    // top-down approach.    for (int i = 2; i <= n; i++)    {        for (int j = 1; j <= i; j++)        {             // n-i in right * i-1 in left            dp[i] = dp[i] + (dp[i - j] *                             dp[j - 1]);        }    }    return dp[n];} // Driver Codepublic static void Main (){    int n = 3;    Console.Write("Number of structurally " +                      "Unique BST with "+ n +                             " keys are : " +                             numberOfBST(n));}} // This code is contributed// by shiv_bhakt.
<?php// PHP code to find number// of unique BSTs Dynamic// Programming solution // Function to find number// of unique BSTfunction numberOfBST($n){     // DP to store the number    // of unique BST with key i    $dp = array($n + 1);    for($i = 0; $i <= $n + 1; $i++)    $dp[$i] = 0;     // Base case    $dp[0] = 1;    $dp[1] = 1;     // fill the dp table    // in top-down approach.    for ($i = 2; $i <= $n; $i++)    {        for ($j = 1; $j <= $i; $j++)        {             // n-i in right *            // i-1 in left            $dp[$i] += (($dp[$i - $j]) *                        ($dp[$j - 1]));        }    }     return $dp[$n];} // Driver Code$n = 3;echo "Number of structurally ".           "Unique BST with " ,          $n , " keys are : " ,              numberOfBST($n) ; // This code is contributed// by shiv_bhakt.?>
Number of structurally Unique BST with 3 keys are : 5
 
Time Complexity: O(n2)  
Vishal_Khoda
rituraj_jain
Gaurav Raj 1
adityakumar129
Algorithms-Dynamic Programming
BST
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Optimal Substructure Property in Dynamic Programming | DP-2
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Maximum sum such that no two elements are adjacent
Gold Mine Problem
Count All Palindrome Sub-Strings in a String | Set 1
3 Different ways to print Fibonacci series in Java
Optimal Binary Search Tree | DP-24
Word Break Problem | DP-32
Binomial Coefficient | DP-9