Number of Unique BST with a given key | Dynamic Programming | Java code to find number of unique BSTs Dynamic Programming solution ; DP to store the number of unique BST with key i ; Base case ; fill the dp table in top - down approach . ; n - i in right * i - 1 in left ; Driver Code
import java . io . * ; import java . util . Arrays ; class GFG { static int numberOfBST ( int n ) { int dp [ ] = new int [ n + 1 ] ; Arrays . fill ( dp , 0 ) ; dp [ 0 ] = 1 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { dp [ i ] = dp [ i ] + ( dp [ i - j ] * dp [ j - 1 ] ) ; } } return dp [ n ] ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( " Number ▁ of ▁ structurally ▁ " + " Unique ▁ BST ▁ with ▁ " + n + " ▁ keys ▁ are ▁ : ▁ " + numberOfBST ( n ) ) ; } }