Given N, Find the total number of unique BSTs that can be made using values from 1 to N.
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:
Number of structurally Unique BST with 3 keys are : 5
Time Complexity: O(n2)
- Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique cap to every person)
- Expected number of moves to reach the end of a board | Dynamic programming
- Bitmasking and Dynamic Programming | Set-2 (TSP)
- Dynamic Programming on Trees | Set 2
- Dynamic Programming on Trees | Set-1
- Dynamic Programming | Building Bridges
- Convert N to M with given operations using dynamic programming
- Double Knapsack | Dynamic Programming
- Greedy approach vs Dynamic programming
- Algorithms | Dynamic Programming | Question 7
- Algorithms | Dynamic Programming | Question 3
- Algorithms | Dynamic Programming | Question 4
- Dynamic Programming vs Divide-and-Conquer
- Algorithms | Dynamic Programming | Question 5
- Top 20 Dynamic Programming Interview Questions
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.